Browse Source

cleanup

custom-ac-example
pbca26 7 years ago
parent
commit
684afdc398
  1. 15
      routes/shepherd/addCoinShortcuts.js
  2. 12
      routes/shepherd/binsUtils.js
  3. 11
      routes/shepherd/coindWalletKeys.js
  4. 8
      routes/shepherd/coinsList.js
  5. 5
      routes/shepherd/confMaxconnections.js
  6. 21
      routes/shepherd/config.js
  7. 12
      routes/shepherd/daemonControl.js
  8. 5
      routes/shepherd/dashboardUpdate.js
  9. 12
      routes/shepherd/debugLog.js
  10. 19
      routes/shepherd/downloadBins.js
  11. 28
      routes/shepherd/downloadPatch.js
  12. 7
      routes/shepherd/downloadUtil.js
  13. 16
      routes/shepherd/downloadZcparams.js
  14. 47
      routes/shepherd/elections.js
  15. 6
      routes/shepherd/electrum/balance.js
  16. 6
      routes/shepherd/electrum/block.js
  17. 15
      routes/shepherd/electrum/createtx-multi.js
  18. 5
      routes/shepherd/electrum/createtx-split.js
  19. 16
      routes/shepherd/electrum/createtx.js
  20. 5
      routes/shepherd/electrum/insight.js
  21. 27
      routes/shepherd/electrum/listunspent.js
  22. 21
      routes/shepherd/electrum/merkle.js
  23. 26
      routes/shepherd/electrum/transactions.js
  24. 2
      routes/shepherd/init.js
  25. 17
      routes/shepherd/log.js
  26. 1
      routes/shepherd/quitDaemon.js
  27. 11
      routes/shepherd/rpc.js

15
routes/shepherd/addCoinShortcuts.js

@ -1,4 +1,7 @@
const electrumServers = require('../electrumjs/electrumServers'); const electrumServers = require('../electrumjs/electrumServers');
const request = require('request');
// TODO: refactor
module.exports = (shepherd) => { module.exports = (shepherd) => {
shepherd.startSPV = (coin) => { shepherd.startSPV = (coin) => {
@ -44,7 +47,7 @@ module.exports = (shepherd) => {
}), }),
}; };
shepherd.request(options, (error, response, body) => { request(options, (error, response, body) => {
if (response && if (response &&
response.statusCode && response.statusCode &&
response.statusCode === 200) { response.statusCode === 200) {
@ -78,7 +81,7 @@ module.exports = (shepherd) => {
}), }),
}; };
shepherd.request(options, (error, response, body) => { request(options, (error, response, body) => {
if (response && if (response &&
response.statusCode && response.statusCode &&
response.statusCode === 200) { response.statusCode === 200) {
@ -112,7 +115,7 @@ module.exports = (shepherd) => {
}), }),
}; };
shepherd.request(options, (error, response, body) => { request(options, (error, response, body) => {
if (response && if (response &&
response.statusCode && response.statusCode &&
response.statusCode === 200) { response.statusCode === 200) {
@ -146,7 +149,7 @@ module.exports = (shepherd) => {
}), }),
}; };
shepherd.request(options, (error, response, body) => { request(options, (error, response, body) => {
if (response && if (response &&
response.statusCode && response.statusCode &&
response.statusCode === 200) { response.statusCode === 200) {
@ -180,7 +183,7 @@ module.exports = (shepherd) => {
}), }),
}; };
shepherd.request(options, (error, response, body) => { request(options, (error, response, body) => {
if (response && if (response &&
response.statusCode && response.statusCode &&
response.statusCode === 200) { response.statusCode === 200) {
@ -231,7 +234,7 @@ module.exports = (shepherd) => {
}), }),
}; };
shepherd.request(options, (error, response, body) => { request(options, (error, response, body) => {
if (response && if (response &&
response.statusCode && response.statusCode &&
response.statusCode === 200) { response.statusCode === 200) {

12
routes/shepherd/binsUtils.js

@ -1,7 +1,11 @@
const os = require('os');
const fsnode = require('fs');
const _fs = require('graceful-fs');
module.exports = (shepherd) => { module.exports = (shepherd) => {
// osx and linux // osx and linux
shepherd.binFixRights = () => { shepherd.binFixRights = () => {
const osPlatform = shepherd.os.platform(); const osPlatform = os.platform();
const _bins = [ const _bins = [
shepherd.komododBin, shepherd.komododBin,
shepherd.komodocliBin shepherd.komodocliBin
@ -10,11 +14,11 @@ module.exports = (shepherd) => {
if (osPlatform === 'darwin' || if (osPlatform === 'darwin' ||
osPlatform === 'linux') { osPlatform === 'linux') {
for (let i = 0; i < _bins.length; i++) { for (let i = 0; i < _bins.length; i++) {
shepherd._fs.stat(_bins[i], (err, stat) => { _fs.stat(_bins[i], (err, stat) => {
if (!err) { if (!err) {
if (parseInt(stat.mode.toString(8), 10) !== 100775) { if (parseInt(stat.mode.toString(8), 10) !== 100775) {
shepherd.log(`${_bins[i]} fix permissions`); shepherd.log(`${_bins[i]} fix permissions`);
shepherd.fsnode.chmodSync(_bins[i], '0775'); fsnode.chmodSync(_bins[i], '0775');
} }
} else { } else {
shepherd.log(`error: ${_bins[i]} not found`); shepherd.log(`error: ${_bins[i]} not found`);
@ -26,8 +30,8 @@ module.exports = (shepherd) => {
shepherd.killRogueProcess = (processName) => { shepherd.killRogueProcess = (processName) => {
// kill rogue process copies on start // kill rogue process copies on start
const osPlatform = os.platform();
let processGrep; let processGrep;
const osPlatform = shepherd.os.platform();
switch (osPlatform) { switch (osPlatform) {
case 'darwin': case 'darwin':

11
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) => { module.exports = (shepherd) => {
/* /*
* type: GET * type: GET
@ -5,8 +10,6 @@ module.exports = (shepherd) => {
*/ */
shepherd.get('/coindwalletkeys', (req, res, next) => { shepherd.get('/coindwalletkeys', (req, res, next) => {
if (shepherd.checkToken(req.query.token)) { if (shepherd.checkToken(req.query.token)) {
const wif = require('wif');
const fs = require('fs');
const chain = req.query.chain; const chain = req.query.chain;
// ref: https://gist.github.com/kendricktan/1e62495150ad236b38616d733aac4eb9 // ref: https://gist.github.com/kendricktan/1e62495150ad236b38616d733aac4eb9
@ -14,7 +17,7 @@ module.exports = (shepherd) => {
_walletDatLocation = chain === 'CHIPS' ? `${shepherd.chipsDir}/wallet.dat` : _walletDatLocation; _walletDatLocation = chain === 'CHIPS' ? `${shepherd.chipsDir}/wallet.dat` : _walletDatLocation;
try { try {
shepherd._fs.access(_walletDatLocation, shepherd.fs.constants.R_OK, (err) => { _fs.access(_walletDatLocation, shepherd.fs.constants.R_OK, (err) => {
if (err) { if (err) {
shepherd.log(`error reading ${_walletDatLocation}`); shepherd.log(`error reading ${_walletDatLocation}`);
successObj = { successObj = {
@ -60,7 +63,7 @@ module.exports = (shepherd) => {
const keyObj = wif.decode(key); const keyObj = wif.decode(key);
const wifKey = wif.encode(keyObj); 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 = { const _keyPair = {
priv: keyPair.toWIF(), priv: keyPair.toWIF(),
pub: keyPair.getAddress(), pub: keyPair.getAddress(),

8
routes/shepherd/coinsList.js

@ -1,3 +1,5 @@
const fs = require('fs-extra');
module.exports = (shepherd) => { module.exports = (shepherd) => {
/* /*
* type: GET * type: GET
@ -5,8 +7,8 @@ module.exports = (shepherd) => {
*/ */
shepherd.get('/coinslist', (req, res, next) => { shepherd.get('/coinslist', (req, res, next) => {
if (shepherd.checkToken(req.query.token)) { if (shepherd.checkToken(req.query.token)) {
if (shepherd.fs.existsSync(`${shepherd.agamaDir}/shepherd/coinslist.json`)) { if (fs.existsSync(`${shepherd.agamaDir}/shepherd/coinslist.json`)) {
shepherd.fs.readFile(`${shepherd.agamaDir}/shepherd/coinslist.json`, 'utf8', (err, data) => { fs.readFile(`${shepherd.agamaDir}/shepherd/coinslist.json`, 'utf8', (err, data) => {
if (err) { if (err) {
const errorObj = { const errorObj = {
msg: 'error', msg: 'error',
@ -57,7 +59,7 @@ module.exports = (shepherd) => {
res.end(JSON.stringify(errorObj)); res.end(JSON.stringify(errorObj));
} else { } 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) { if (err) {
const errorObj = { const errorObj = {
msg: 'error', msg: 'error',

5
routes/shepherd/confMaxconnections.js

@ -1,8 +1,9 @@
const fs = require('fs-extra'); const fs = require('fs-extra');
const Promise = require('bluebird');
module.exports = (shepherd) => { module.exports = (shepherd) => {
shepherd.getMaxconKMDConf = () => { shepherd.getMaxconKMDConf = () => {
return new shepherd.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
fs.readFile(`${shepherd.komodoDir}/komodo.conf`, 'utf8', (err, data) => { fs.readFile(`${shepherd.komodoDir}/komodo.conf`, 'utf8', (err, data) => {
if (err) { if (err) {
shepherd.log('kmd conf maxconnections param read failed'); shepherd.log('kmd conf maxconnections param read failed');
@ -23,7 +24,7 @@ module.exports = (shepherd) => {
} }
shepherd.setMaxconKMDConf = (limit) => { shepherd.setMaxconKMDConf = (limit) => {
return new shepherd.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
fs.readFile(`${shepherd.komodoDir}/komodo.conf`, 'utf8', (err, data) => { fs.readFile(`${shepherd.komodoDir}/komodo.conf`, 'utf8', (err, data) => {
const _maxconVal = limit ? 1 : 10; const _maxconVal = limit ? 1 : 10;

21
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) => { module.exports = (shepherd) => {
shepherd.loadLocalConfig = () => { shepherd.loadLocalConfig = () => {
if (shepherd.fs.existsSync(`${shepherd.agamaDir}/config.json`)) { if (fs.existsSync(`${shepherd.agamaDir}/config.json`)) {
let localAppConfig = shepherd.fs.readFileSync(`${shepherd.agamaDir}/config.json`, 'utf8'); let localAppConfig = fs.readFileSync(`${shepherd.agamaDir}/config.json`, 'utf8');
shepherd.log('app config set from local file'); shepherd.log('app config set from local file');
shepherd.writeLog('app config set from local file'); shepherd.writeLog('app config set from local file');
@ -53,14 +58,14 @@ module.exports = (shepherd) => {
shepherd.saveLocalAppConf = (appSettings) => { shepherd.saveLocalAppConf = (appSettings) => {
let appConfFileName = `${shepherd.agamaDir}/config.json`; 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) { if (!err) {
const FixFilePermissions = () => { const FixFilePermissions = () => {
return new shepherd.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const result = 'config.json file permissions updated to Read/Write'; const result = 'config.json file permissions updated to Read/Write';
shepherd.fsnode.chmodSync(appConfFileName, '0666'); fsnode.chmodSync(appConfFileName, '0666');
setTimeout(() => { setTimeout(() => {
shepherd.log(result); shepherd.log(result);
@ -71,10 +76,10 @@ module.exports = (shepherd) => {
} }
const FsWrite = () => { const FsWrite = () => {
return new shepherd.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const result = 'config.json write file is done'; const result = 'config.json write file is done';
shepherd.fs.writeFile(appConfFileName, fs.writeFile(appConfFileName,
JSON.stringify(appSettings) JSON.stringify(appSettings)
.replace(/,/g, ',\n') // format json in human readable form .replace(/,/g, ',\n') // format json in human readable form
.replace(/":/g, '": ') .replace(/":/g, '": ')
@ -84,7 +89,7 @@ module.exports = (shepherd) => {
return shepherd.log(err); return shepherd.log(err);
}); });
shepherd.fsnode.chmodSync(appConfFileName, '0666'); fsnode.chmodSync(appConfFileName, '0666');
setTimeout(() => { setTimeout(() => {
shepherd.log(result); shepherd.log(result);
shepherd.log(`app conf.json file is created successfully at: ${shepherd.agamaDir}`); shepherd.log(`app conf.json file is created successfully at: ${shepherd.agamaDir}`);

12
routes/shepherd/daemonControl.js

@ -58,12 +58,12 @@ module.exports = (shepherd) => {
} }
break; break;
case 'coind': 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; break;
default: default:
DaemonConfPath = `${shepherd.komodoDir}/${flock}`; DaemonConfPath = `${shepherd.komodoDir}/${flock}`;
if (_platform === 'win32') { 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'); let spawnErr = fs.openSync(_daemonLogName, 'a');
spawn(shepherd.komododBin, _arg, { spawn(shepherd.komododBin, _arg, {
stdio: ['ignore', spawnOut, spawnErr], stdio: [
'ignore',
spawnOut,
spawnErr
],
detached: true, detached: true,
}).unref(); }).unref();
} else { } else {
@ -609,7 +613,7 @@ module.exports = (shepherd) => {
shepherd.log('rpcuser: OK'); shepherd.log('rpcuser: OK');
shepherd.writeLog('rpcuser: OK'); shepherd.writeLog('rpcuser: OK');
} else { } 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.log('rpcuser: NOT FOUND');
shepherd.writeLog('rpcuser: NOT FOUND'); shepherd.writeLog('rpcuser: NOT FOUND');

5
routes/shepherd/dashboardUpdate.js

@ -1,4 +1,5 @@
const Promise = require('bluebird'); const Promise = require('bluebird');
const request = require('request');
module.exports = (shepherd) => { module.exports = (shepherd) => {
/* /*
@ -24,7 +25,7 @@ module.exports = (shepherd) => {
_promiseStack = [ _promiseStack = [
'getinfo', 'getinfo',
'listtransactions', 'listtransactions',
'getbalance', 'getbalance'
]; ];
} else { } else {
_returnObj = { _returnObj = {
@ -272,7 +273,7 @@ module.exports = (shepherd) => {
timeout: 120000, timeout: 120000,
}; };
shepherd.request(options, (error, response, body) => { request(options, (error, response, body) => {
if (response && if (response &&
response.statusCode && response.statusCode &&
response.statusCode === 200) { response.statusCode === 200) {

12
routes/shepherd/debugLog.js

@ -1,3 +1,7 @@
const path = require('path');
const _fs = require('graceful-fs');
const Promise = require('bluebird');
module.exports = (shepherd) => { module.exports = (shepherd) => {
/* /*
* type: POST * type: POST
@ -20,7 +24,7 @@ module.exports = (shepherd) => {
if (shepherd.os.platform() === 'win32') { if (shepherd.os.platform() === 'win32') {
shepherd.komodoDir = shepherd.appConfig.dataDir.length ? shepherd.appConfig.dataDir : `${process.env.APPDATA}/Komodo`; 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') { if (_herd === 'komodo') {
@ -93,18 +97,18 @@ module.exports = (shepherd) => {
}); });
shepherd.readDebugLog = (fileLocation, lastNLines) => { shepherd.readDebugLog = (fileLocation, lastNLines) => {
return new shepherd.Promise( return new Promise(
(resolve, reject) => { (resolve, reject) => {
if (lastNLines) { if (lastNLines) {
try { try {
shepherd._fs.access(fileLocation, shepherd.fs.constants.R_OK, (err) => { _fs.access(fileLocation, shepherd.fs.constants.R_OK, (err) => {
if (err) { if (err) {
shepherd.log(`error reading ${fileLocation}`); shepherd.log(`error reading ${fileLocation}`);
shepherd.writeLog(`error reading ${fileLocation}`); shepherd.writeLog(`error reading ${fileLocation}`);
reject(`readDebugLog error: ${err}`); reject(`readDebugLog error: ${err}`);
} else { } else {
shepherd.log(`reading ${fileLocation}`); shepherd.log(`reading ${fileLocation}`);
shepherd._fs.readFile(fileLocation, 'utf-8', (err, data) => { _fs.readFile(fileLocation, 'utf-8', (err, data) => {
if (err) { if (err) {
shepherd.writeLog(`readDebugLog err: ${err}`); shepherd.writeLog(`readDebugLog err: ${err}`);
shepherd.log(`readDebugLog err: ${err}`); shepherd.log(`readDebugLog err: ${err}`);

19
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 = { const remoteBinLocation = {
win32: 'https://artifacts.supernet.org/latest/windows/', win32: 'https://artifacts.supernet.org/latest/windows/',
darwin: 'https://artifacts.supernet.org/latest/osx/', darwin: 'https://artifacts.supernet.org/latest/osx/',
@ -47,7 +52,7 @@ module.exports = (shepherd) => {
// TODO: promises // TODO: promises
shepherd.get('/update/bins/check', (req, res, next) => { shepherd.get('/update/bins/check', (req, res, next) => {
if (shepherd.checkToken(req.query.token)) { if (shepherd.checkToken(req.query.token)) {
const rootLocation = shepherd.path.join(__dirname, '../../'); const rootLocation = path.join(__dirname, '../../');
const successObj = { const successObj = {
msg: 'success', msg: 'success',
result: 'bins', result: 'bins',
@ -55,7 +60,7 @@ module.exports = (shepherd) => {
res.end(JSON.stringify(successObj)); res.end(JSON.stringify(successObj));
const _os = shepherd.os.platform(); const _os = os.platform();
shepherd.log(`checking bins: ${_os}`); shepherd.log(`checking bins: ${_os}`);
shepherd.io.emit('patch', { shepherd.io.emit('patch', {
@ -67,8 +72,8 @@ module.exports = (shepherd) => {
}); });
// get list of bins/dlls that can be updated to the latest // get list of bins/dlls that can be updated to the latest
for (let i = 0; i < latestBins[_os].length; i++) { for (let i = 0; i < latestBins[_os].length; i++) {
shepherd.remoteFileSize(remoteBinLocation[_os] + latestBins[_os][i], (err, remoteBinSize) => { remoteFileSize(remoteBinLocation[_os] + latestBins[_os][i], (err, remoteBinSize) => {
const localBinSize = shepherd.fs.statSync(rootLocation + localBinLocation[_os] + latestBins[_os][i]).size; const localBinSize = fs.statSync(rootLocation + localBinLocation[_os] + latestBins[_os][i]).size;
shepherd.log('remote url: ' + (remoteBinLocation[_os] + latestBins[_os][i]) + ' (' + remoteBinSize + ')'); shepherd.log('remote url: ' + (remoteBinLocation[_os] + latestBins[_os][i]) + ' (' + remoteBinSize + ')');
shepherd.log('local file: ' + (rootLocation + localBinLocation[_os] + latestBins[_os][i]) + ' (' + localBinSize + ')'); 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) => { shepherd.get('/update/bins', (req, res, next) => {
if (shepherd.checkToken(req.query.token)) { if (shepherd.checkToken(req.query.token)) {
const rootLocation = shepherd.path.join(__dirname, '../../'); const rootLocation = path.join(__dirname, '../../');
const _os = shepherd.os.platform(); const _os = os.platform();
const successObj = { const successObj = {
msg: 'success', msg: 'success',
result: { result: {
@ -145,7 +150,7 @@ module.exports = (shepherd) => {
}) })
.then(() => { .then(() => {
// verify that remote file is matching to DL'ed file // 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'); shepherd.log('compare dl file size');
if (localBinSize === binsToUpdate[i].rSize) { if (localBinSize === binsToUpdate[i].rSize) {

28
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) => { module.exports = (shepherd) => {
/* /*
* DL app patch * DL app patch
@ -25,7 +31,7 @@ module.exports = (shepherd) => {
}); });
shepherd.updateAgama = () => { shepherd.updateAgama = () => {
const rootLocation = shepherd.path.join(__dirname, '../../'); const rootLocation = path.join(__dirname, '../../');
shepherd.downloadFile({ shepherd.downloadFile({
remoteFile: 'https://github.com/pbca26/dl-test/raw/master/patch.zip', remoteFile: 'https://github.com/pbca26/dl-test/raw/master/patch.zip',
@ -50,18 +56,18 @@ module.exports = (shepherd) => {
.then(() => { .then(() => {
shepherd.remoteFileSize('https://github.com/pbca26/dl-test/raw/master/patch.zip', (err, remotePatchSize) => { shepherd.remoteFileSize('https://github.com/pbca26/dl-test/raw/master/patch.zip', (err, remotePatchSize) => {
// verify that remote file is matching to DL'ed file // 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'); shepherd.log('compare dl file size');
if (localPatchSize === remotePatchSize) { 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('patch succesfully downloaded');
shepherd.log('extracting contents'); shepherd.log('extracting contents');
if (shepherd.appConfig.dev) { if (shepherd.appConfig.dev) {
if (!shepherd.fs.existsSync(`${rootLocation}/patch`)) { if (!fs.existsSync(`${rootLocation}/patch`)) {
shepherd.fs.mkdirSync(`${rootLocation}/patch`); fs.mkdirSync(`${rootLocation}/patch`);
} }
} }
@ -73,7 +79,7 @@ module.exports = (shepherd) => {
status: 'done', status: 'done',
}, },
}); });
shepherd.fs.unlinkSync(`${rootLocation}patch.zip`); fs.unlinkSync(`${rootLocation}patch.zip`);
} else { } else {
shepherd.io.emit('patch', { shepherd.io.emit('patch', {
msg: { msg: {
@ -95,18 +101,18 @@ module.exports = (shepherd) => {
*/ */
shepherd.get('/update/patch/check', (req, res, next) => { shepherd.get('/update/patch/check', (req, res, next) => {
if (shepherd.checkToken(req.query.token)) { if (shepherd.checkToken(req.query.token)) {
const rootLocation = shepherd.path.join(__dirname, '../../'); const rootLocation = path.join(__dirname, '../../');
const options = { const options = {
url: 'https://github.com/pbca26/dl-test/raw/master/version', url: 'https://github.com/pbca26/dl-test/raw/master/version',
method: 'GET', method: 'GET',
}; };
shepherd.request(options, (error, response, body) => { request(options, (error, response, body) => {
if (response && if (response &&
response.statusCode && response.statusCode &&
response.statusCode === 200) { response.statusCode === 200) {
const remoteVersion = body.split('\n'); const remoteVersion = body.split('\n');
const localVersionFile = shepherd.fs.readFileSync(`${rootLocation}version`, 'utf8'); const localVersionFile = fs.readFileSync(`${rootLocation}version`, 'utf8');
let localVersion; let localVersion;
if (localVersionFile.indexOf('\r\n') > -1) { if (localVersionFile.indexOf('\r\n') > -1) {
@ -157,8 +163,8 @@ module.exports = (shepherd) => {
*/ */
shepherd.get('/unpack', (req, res, next) => { shepherd.get('/unpack', (req, res, next) => {
if (shepherd.checkToken(req.query.token)) { if (shepherd.checkToken(req.query.token)) {
const dlLocation = shepherd.path.join(__dirname, '../../'); const dlLocation = path.join(__dirname, '../../');
const zip = new shepherd.AdmZip(`${dlLocation}patch.zip`); const zip = new AdmZip(`${dlLocation}patch.zip`);
zip.extractAllTo(/*target path*/ `${dlLocation}/patch/unpack`, /*overwrite*/true); zip.extractAllTo(/*target path*/ `${dlLocation}/patch/unpack`, /*overwrite*/true);
const successObj = { const successObj = {

7
routes/shepherd/downloadUtil.js

@ -1,9 +1,12 @@
const Promise = require('bluebird');
const fs = require('fs-extra');
module.exports = (shepherd) => { module.exports = (shepherd) => {
/** /**
* Promise based download file method * Promise based download file method
*/ */
shepherd.downloadFile = (configuration) => { shepherd.downloadFile = (configuration) => {
return new shepherd.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// Save variable to know progress // Save variable to know progress
let receivedBytes = 0; let receivedBytes = 0;
let totalBytes = 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.pipe(out);
req.on('response', (data) => { req.on('response', (data) => {

16
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) => { module.exports = (shepherd) => {
shepherd.zcashParamsDownloadLinks = { shepherd.zcashParamsDownloadLinks = {
'agama.komodoplatform.com': { 'agama.komodoplatform.com': {
@ -16,10 +20,10 @@ module.exports = (shepherd) => {
shepherd.zcashParamsExist = () => { shepherd.zcashParamsExist = () => {
let _checkList = { let _checkList = {
rootDir: shepherd._fs.existsSync(shepherd.zcashParamsDir), rootDir: _fs.existsSync(shepherd.zcashParamsDir),
provingKey: shepherd._fs.existsSync(`${shepherd.zcashParamsDir}/sprout-proving.key`), provingKey: _fs.existsSync(`${shepherd.zcashParamsDir}/sprout-proving.key`),
provingKeySize: false, provingKeySize: false,
verifyingKey: shepherd._fs.existsSync(`${shepherd.zcashParamsDir}/sprout-verifying.key`), verifyingKey: _fs.existsSync(`${shepherd.zcashParamsDir}/sprout-verifying.key`),
verifyingKeySize: false, verifyingKeySize: false,
errors: false, errors: false,
}; };
@ -28,8 +32,8 @@ module.exports = (shepherd) => {
_checkList.provingKey || _checkList.provingKey ||
_checkList.verifyingKey) { _checkList.verifyingKey) {
// verify each key size // verify each key size
const _provingKeySize = _checkList.provingKey ? shepherd.fs.lstatSync(`${shepherd.zcashParamsDir}/sprout-proving.key`) : 0; const _provingKeySize = _checkList.provingKey ? fs.lstatSync(`${shepherd.zcashParamsDir}/sprout-proving.key`) : 0;
const _verifyingKeySize = _checkList.verifyingKey ? shepherd.fs.lstatSync(`${shepherd.zcashParamsDir}/sprout-verifying.key`) : 0; const _verifyingKeySize = _checkList.verifyingKey ? fs.lstatSync(`${shepherd.zcashParamsDir}/sprout-verifying.key`) : 0;
if (Number(_provingKeySize.size) === 910173851) { // bytes if (Number(_provingKeySize.size) === 910173851) { // bytes
_checkList.provingKeySize = true; _checkList.provingKeySize = true;
@ -55,7 +59,7 @@ module.exports = (shepherd) => {
} }
shepherd.zcashParamsExistPromise = () => { shepherd.zcashParamsExistPromise = () => {
return new shepherd.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const _verify = shepherd.zcashParamsExist(); const _verify = shepherd.zcashParamsExist();
resolve(_verify); resolve(_verify);
}); });

47
routes/shepherd/elections.js

@ -1,5 +1,6 @@
const bs58check = require('bs58check'); const bs58check = require('bs58check');
const bitcoin = require('bitcoinjs-lib'); const bitcoin = require('bitcoinjs-lib');
const Promise = require('bluebird');
module.exports = (shepherd) => { module.exports = (shepherd) => {
shepherd.elections = {}; shepherd.elections = {};
@ -111,11 +112,11 @@ module.exports = (shepherd) => {
shepherd.electionsDecodeTx = (decodedTx, ecl, network, _network, transaction, blockInfo, address) => { shepherd.electionsDecodeTx = (decodedTx, ecl, network, _network, transaction, blockInfo, address) => {
let txInputs = []; let txInputs = [];
return new shepherd.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (decodedTx && if (decodedTx &&
decodedTx.inputs) { decodedTx.inputs) {
shepherd.Promise.all(decodedTx.inputs.map((_decodedInput, index) => { Promise.all(decodedTx.inputs.map((_decodedInput, index) => {
return new shepherd.Promise((_resolve, _reject) => { return new Promise((_resolve, _reject) => {
if (_decodedInput.txid !== '0000000000000000000000000000000000000000000000000000000000000000') { if (_decodedInput.txid !== '0000000000000000000000000000000000000000000000000000000000000000') {
ecl.blockchainTransactionGet(_decodedInput.txid) ecl.blockchainTransactionGet(_decodedInput.txid)
.then((rawInput) => { .then((rawInput) => {
@ -186,8 +187,8 @@ module.exports = (shepherd) => {
shepherd.log(json.length, true); shepherd.log(json.length, true);
shepherd.Promise.all(json.map((transaction, index) => { Promise.all(json.map((transaction, index) => {
return new shepherd.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
ecl.blockchainBlockGetHeader(transaction.height) ecl.blockchainBlockGetHeader(transaction.height)
.then((blockInfo) => { .then((blockInfo) => {
if (blockInfo && if (blockInfo &&
@ -256,7 +257,8 @@ module.exports = (shepherd) => {
if (type === 'candidate') { if (type === 'candidate') {
if (_region === 'ne2k18-na-1-eu-2-ae-3-sh-4') { 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 = [ const _regionsLookup = [
'ne2k18-na', 'ne2k18-na',
'ne2k18-eu', 'ne2k18-eu',
@ -264,7 +266,15 @@ module.exports = (shepherd) => {
'ne2k18-sh' 'ne2k18-sh'
]; ];
shepherd.electionsDecodeTx(decodedTx, ecl, network, _network, transaction, blockInfo, _address) shepherd.electionsDecodeTx(
decodedTx,
ecl,
network,
_network,
transaction,
blockInfo,
_address
)
.then((res) => { .then((res) => {
shepherd.log(`i received ${decodedTx.outputs[i].value} from ${res.outputAddresses[0]} out ${i} region ${_regionsLookup[i]}`); shepherd.log(`i received ${decodedTx.outputs[i].value} from ${res.outputAddresses[0]} out ${i} region ${_regionsLookup[i]}`);
_rawtx.push({ _rawtx.push({
@ -277,7 +287,15 @@ module.exports = (shepherd) => {
}); });
} }
} else { } else {
shepherd.electionsDecodeTx(decodedTx, ecl, network, _network, transaction, blockInfo, _address) shepherd.electionsDecodeTx(
decodedTx,
ecl,
network,
_network,
transaction,
blockInfo,
_address
)
.then((res) => { .then((res) => {
if (decodedTx.outputs[i].scriptPubKey.addresses[0] === _address) { if (decodedTx.outputs[i].scriptPubKey.addresses[0] === _address) {
_candidate.amount = decodedTx.outputs[i].value; _candidate.amount = decodedTx.outputs[i].value;
@ -298,7 +316,15 @@ module.exports = (shepherd) => {
} }
} else { } else {
shepherd.log('elections regular tx', true); 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) => { .then((_regularTx) => {
if (_regularTx[0] && if (_regularTx[0] &&
_regularTx[1]) { _regularTx[1]) {
@ -311,7 +337,8 @@ module.exports = (shepherd) => {
hash: transaction['tx_hash'], hash: transaction['tx_hash'],
}); });
} else { } 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({ _rawtx.push({
address: _regularTx.address || 'self', address: _regularTx.address || 'self',
timestamp: _regularTx.timestamp, timestamp: _regularTx.timestamp,

6
routes/shepherd/electrum/balance.js

@ -1,3 +1,5 @@
const Promise = require('bluebird');
module.exports = (shepherd) => { module.exports = (shepherd) => {
shepherd.get('/electrum/getbalance', (req, res, next) => { shepherd.get('/electrum/getbalance', (req, res, next) => {
if (shepherd.checkToken(req.query.token)) { if (shepherd.checkToken(req.query.token)) {
@ -35,8 +37,8 @@ module.exports = (shepherd) => {
_utxo.length) { _utxo.length) {
let interestTotal = 0; let interestTotal = 0;
shepherd.Promise.all(_utxo.map((_utxoItem, index) => { Promise.all(_utxo.map((_utxoItem, index) => {
return new shepherd.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
shepherd.getTransaction(_utxoItem['tx_hash'], network, ecl) shepherd.getTransaction(_utxoItem['tx_hash'], network, ecl)
.then((_rawtxJSON) => { .then((_rawtxJSON) => {
shepherd.log('electrum gettransaction ==>', true); shepherd.log('electrum gettransaction ==>', true);

6
routes/shepherd/electrum/block.js

@ -1,3 +1,5 @@
const Promise = require('bluebird');
module.exports = (shepherd) => { module.exports = (shepherd) => {
shepherd.get('/electrum/getblockinfo', (req, res, next) => { shepherd.get('/electrum/getblockinfo', (req, res, next) => {
if (shepherd.checkToken(req.query.token)) { if (shepherd.checkToken(req.query.token)) {
@ -21,7 +23,7 @@ module.exports = (shepherd) => {
}); });
shepherd.electrumGetBlockInfo = (height, network) => { 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 const ecl = new shepherd.electrumJSCore(shepherd.electrumServers[network].port, shepherd.electrumServers[network].address, shepherd.electrumServers[network].proto); // tcp or tls
ecl.connect(); ecl.connect();
@ -58,7 +60,7 @@ module.exports = (shepherd) => {
}); });
shepherd.electrumGetCurrentBlock = (network) => { 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 const ecl = new shepherd.electrumJSCore(shepherd.electrumServers[network].port, shepherd.electrumServers[network].address, shepherd.electrumServers[network].proto); // tcp or tls
ecl.connect(); ecl.connect();

15
routes/shepherd/electrum/createtx-multi.js

@ -1,6 +1,8 @@
const bitcoinJS = require('bitcoinjs-lib');
const bitcoinJSForks = require('bitcoinforksjs-lib'); const bitcoinJSForks = require('bitcoinforksjs-lib');
const bitcoinZcash = require('bitcoinjs-lib-zcash'); const bitcoinZcash = require('bitcoinjs-lib-zcash');
const bitcoinPos = require('bitcoinjs-lib-pos'); const bitcoinPos = require('bitcoinjs-lib-pos');
const coinSelect = require('coinselect');
// not prod ready, only for voting! // not prod ready, only for voting!
// needs a fix // needs a fix
@ -94,7 +96,7 @@ module.exports = (shepherd) => {
// default coin selection algo blackjack with fallback to accumulative // default coin selection algo blackjack with fallback to accumulative
// make a first run, calc approx tx fee // make a first run, calc approx tx fee
// if ins and outs are empty reduce max spend by txfee // 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 inputs = firstRun.inputs;
let outputs = firstRun.outputs; let outputs = firstRun.outputs;
@ -117,7 +119,7 @@ module.exports = (shepherd) => {
shepherd.log('coinselect adjusted targets =>', true); shepherd.log('coinselect adjusted targets =>', true);
shepherd.log(targets, true); shepherd.log(targets, true);
const secondRun = shepherd.coinSelect(utxoListFormatted, targets, 0); const secondRun = coinSelect(utxoListFormatted, targets, 0);
inputs = secondRun.inputs; inputs = secondRun.inputs;
outputs = secondRun.outputs; outputs = secondRun.outputs;
fee = fee ? fee : secondRun.fee; fee = fee ? fee : secondRun.fee;
@ -427,7 +429,7 @@ module.exports = (shepherd) => {
// single sig // single sig
shepherd.buildSignedTxMulti = (sendTo, changeAddress, wif, network, utxo, changeValue, spendValue, opreturn) => { 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; let tx;
if (shepherd.isZcash(network)) { if (shepherd.isZcash(network)) {
@ -435,7 +437,7 @@ module.exports = (shepherd) => {
} else if (shepherd.isPos(network)) { } else if (shepherd.isPos(network)) {
tx = new bitcoinPos.TransactionBuilder(shepherd.getNetworkData(network)); tx = new bitcoinPos.TransactionBuilder(shepherd.getNetworkData(network));
} else { } else {
tx = new shepherd.bitcoinJS.TransactionBuilder(shepherd.getNetworkData(network)); tx = new bitcoinJS.TransactionBuilder(shepherd.getNetworkData(network));
} }
shepherd.log('buildSignedTx', true); shepherd.log('buildSignedTx', true);
@ -466,10 +468,11 @@ module.exports = (shepherd) => {
if (opreturn && if (opreturn &&
opreturn.length) { opreturn.length) {
for (let i = 0; i < opreturn.length; i++) { for (let i = 0; i < opreturn.length; i++) {
shepherd.log(`opreturn ${i} ${opreturn[i]}`);
const data = Buffer.from(opreturn[i], 'utf8'); 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); tx.addOutput(dataScript, 1000);
shepherd.log(`opreturn ${i} ${opreturn[i]}`);
} }
} }

5
routes/shepherd/electrum/createtx-split.js

@ -1,3 +1,4 @@
const bitcoinJS = require('bitcoinjs-lib');
const bitcoinJSForks = require('bitcoinforksjs-lib'); const bitcoinJSForks = require('bitcoinforksjs-lib');
const bitcoinZcash = require('bitcoinjs-lib-zcash'); const bitcoinZcash = require('bitcoinjs-lib-zcash');
const bitcoinPos = require('bitcoinjs-lib-pos'); const bitcoinPos = require('bitcoinjs-lib-pos');
@ -14,7 +15,7 @@ module.exports = (shepherd) => {
const outputAddress = req.body.payload.outputAddress; const outputAddress = req.body.payload.outputAddress;
const changeAddress = req.body.payload.changeAddress; 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; let tx;
if (shepherd.isZcash(network)) { if (shepherd.isZcash(network)) {
@ -22,7 +23,7 @@ module.exports = (shepherd) => {
} else if (shepherd.isPos(network)) { } else if (shepherd.isPos(network)) {
tx = new bitcoinPos.TransactionBuilder(shepherd.getNetworkData(network)); tx = new bitcoinPos.TransactionBuilder(shepherd.getNetworkData(network));
} else { } else {
tx = new shepherd.bitcoinJS.TransactionBuilder(shepherd.getNetworkData(network)); tx = new bitcoinJS.TransactionBuilder(shepherd.getNetworkData(network));
} }
shepherd.log('buildSignedTx', true); shepherd.log('buildSignedTx', true);

16
routes/shepherd/electrum/createtx.js

@ -1,6 +1,8 @@
const bitcoinJS = require('bitcoinjs-lib');
const bitcoinJSForks = require('bitcoinforksjs-lib'); const bitcoinJSForks = require('bitcoinforksjs-lib');
const bitcoinZcash = require('bitcoinjs-lib-zcash'); const bitcoinZcash = require('bitcoinjs-lib-zcash');
const bitcoinPos = require('bitcoinjs-lib-pos'); const bitcoinPos = require('bitcoinjs-lib-pos');
const coinSelect = require('coinselect');
module.exports = (shepherd) => { module.exports = (shepherd) => {
// unsigned tx // unsigned tx
@ -9,11 +11,11 @@ module.exports = (shepherd) => {
// TODO: finish unsigned for zcash, btc forks and pos coins // TODO: finish unsigned for zcash, btc forks and pos coins
if (network === 'btg') { if (network === 'btg') {
shepherd.log('enable btg', true);
tx = new bitcoinJSForks.TransactionBuilder(shepherd.getNetworkData(network)); tx = new bitcoinJSForks.TransactionBuilder(shepherd.getNetworkData(network));
tx.enableBitcoinGold(true); tx.enableBitcoinGold(true);
shepherd.log('enable btg', true);
} else { } else {
tx = new shepherd.bitcoinJS.TransactionBuilder(shepherd.getNetworkData(network)); tx = new bitcoinJS.TransactionBuilder(shepherd.getNetworkData(network));
} }
shepherd.log('buildSignedTx', true); shepherd.log('buildSignedTx', true);
@ -55,7 +57,7 @@ module.exports = (shepherd) => {
// single sig // single sig
shepherd.buildSignedTx = (sendTo, changeAddress, wif, network, utxo, changeValue, spendValue, opreturn) => { 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; let tx;
if (shepherd.isZcash(network)) { if (shepherd.isZcash(network)) {
@ -63,7 +65,7 @@ module.exports = (shepherd) => {
} else if (shepherd.isPos(network)) { } else if (shepherd.isPos(network)) {
tx = new bitcoinPos.TransactionBuilder(shepherd.getNetworkData(network)); tx = new bitcoinPos.TransactionBuilder(shepherd.getNetworkData(network));
} else { } else {
tx = new shepherd.bitcoinJS.TransactionBuilder(shepherd.getNetworkData(network)); tx = new bitcoinJS.TransactionBuilder(shepherd.getNetworkData(network));
} }
shepherd.log('buildSignedTx', true); shepherd.log('buildSignedTx', true);
@ -90,10 +92,10 @@ module.exports = (shepherd) => {
} }
if (opreturn) { if (opreturn) {
console.log(`opreturn ${opreturn}`);
const data = Buffer.from(opreturn, 'utf8'); const data = Buffer.from(opreturn, 'utf8');
const dataScript = shepherd.bitcoinJS.script.nullData.output.encode(data); const dataScript = shepherd.bitcoinJS.script.nullData.output.encode(data);
tx.addOutput(dataScript, 1000); tx.addOutput(dataScript, 1000);
console.log(`opreturn ${opreturn}`);
} }
if (network === 'komodo' || if (network === 'komodo' ||
@ -279,7 +281,7 @@ module.exports = (shepherd) => {
// default coin selection algo blackjack with fallback to accumulative // default coin selection algo blackjack with fallback to accumulative
// make a first run, calc approx tx fee // make a first run, calc approx tx fee
// if ins and outs are empty reduce max spend by txfee // 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 inputs = firstRun.inputs;
let outputs = firstRun.outputs; let outputs = firstRun.outputs;
@ -302,7 +304,7 @@ module.exports = (shepherd) => {
shepherd.log('coinselect adjusted targets =>', true); shepherd.log('coinselect adjusted targets =>', true);
shepherd.log(targets, true); shepherd.log(targets, true);
const secondRun = shepherd.coinSelect(utxoListFormatted, targets, 0); const secondRun = coinSelect(utxoListFormatted, targets, 0);
inputs = secondRun.inputs; inputs = secondRun.inputs;
outputs = secondRun.outputs; outputs = secondRun.outputs;
fee = fee ? fee : secondRun.fee; fee = fee ? fee : secondRun.fee;

5
routes/shepherd/electrum/insight.js

@ -1,4 +1,5 @@
const request = require('request'); const request = require('request');
const Promise = require('bluebird');
// abstraction layer to communicate with insight explorers // abstraction layer to communicate with insight explorers
@ -55,7 +56,7 @@ module.exports = (shepherd) => {
blockchainAddressGetBalance: (address) => { blockchainAddressGetBalance: (address) => {
shepherd.log('insight blockchainAddressGetBalance', true); shepherd.log('insight blockchainAddressGetBalance', true);
return new shepherd.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let options = { let options = {
url: `${shepherd.insightJSCoreActiveCoin.address}/${apiRoutes('utxo', address)}`, url: `${shepherd.insightJSCoreActiveCoin.address}/${apiRoutes('utxo', address)}`,
method: 'GET', method: 'GET',
@ -97,7 +98,7 @@ module.exports = (shepherd) => {
blockchainAddressListunspent: (address) => { blockchainAddressListunspent: (address) => {
shepherd.log('insight blockchainAddressListunspent', true); shepherd.log('insight blockchainAddressListunspent', true);
return new shepherd.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let options = { let options = {
url: `${shepherd.insightJSCoreActiveCoin.address}/${apiRoutes('utxo', address)}`, url: `${shepherd.insightJSCoreActiveCoin.address}/${apiRoutes('utxo', address)}`,
method: 'GET', method: 'GET',

27
routes/shepherd/electrum/listunspent.js

@ -1,11 +1,14 @@
// TODO: watchonly spendable switch // TODO: watchonly spendable switch
const Promise = require('bluebird');
module.exports = (shepherd) => { module.exports = (shepherd) => {
shepherd.listunspent = (ecl, address, network, full, verify) => { shepherd.listunspent = (ecl, address, network, full, verify) => {
let _atLeastOneDecodeTxFailed = false; let _atLeastOneDecodeTxFailed = false;
if (full && !ecl.insight) { if (full &&
return new shepherd.Promise((resolve, reject) => { !ecl.insight) {
return new Promise((resolve, reject) => {
ecl.connect(); ecl.connect();
ecl.blockchainAddressListunspent(address) ecl.blockchainAddressListunspent(address)
.then((_utxoJSON) => { .then((_utxoJSON) => {
@ -29,12 +32,12 @@ module.exports = (shepherd) => {
ecl.close(); ecl.close();
resolve('no valid utxo'); resolve('no valid utxo');
} else { } else {
shepherd.Promise.all(_utxo.map((_utxoItem, index) => { Promise.all(_utxo.map((_utxoItem, index) => {
return new shepherd.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
shepherd.getTransaction(_utxoItem['tx_hash'], network, ecl) shepherd.getTransaction(_utxoItem['tx_hash'], network, ecl)
.then((_rawtxJSON) => { .then((_rawtxJSON) => {
shepherd.log('electrum gettransaction ==>', true); shepherd.log('electrum gettransaction ==>', true);
shepherd.log(index + ' | ' + (_rawtxJSON.length - 1), true); shepherd.log(`${index} | ${(_rawtxJSON.length - 1)}`, true);
shepherd.log(_rawtxJSON, true); shepherd.log(_rawtxJSON, true);
// decode tx // decode tx
@ -72,7 +75,11 @@ module.exports = (shepherd) => {
// merkle root verification against another electrum server // merkle root verification against another electrum server
if (verify) { if (verify) {
shepherd.verifyMerkleByCoin(shepherd.findCoinName(network), _utxoItem['tx_hash'], _utxoItem.height) shepherd.verifyMerkleByCoin(
shepherd.findCoinName(network),
_utxoItem['tx_hash'],
_utxoItem.height
)
.then((verifyMerkleRes) => { .then((verifyMerkleRes) => {
if (verifyMerkleRes && if (verifyMerkleRes &&
verifyMerkleRes === shepherd.CONNECTION_ERROR_OR_INCOMPLETE_DATA) { verifyMerkleRes === shepherd.CONNECTION_ERROR_OR_INCOMPLETE_DATA) {
@ -99,7 +106,11 @@ module.exports = (shepherd) => {
// merkle root verification against another electrum server // merkle root verification against another electrum server
if (verify) { if (verify) {
shepherd.verifyMerkleByCoin(shepherd.findCoinName(network), _utxoItem['tx_hash'], _utxoItem.height) shepherd.verifyMerkleByCoin(
shepherd.findCoinName(network),
_utxoItem['tx_hash'],
_utxoItem.height
)
.then((verifyMerkleRes) => { .then((verifyMerkleRes) => {
if (verifyMerkleRes && if (verifyMerkleRes &&
verifyMerkleRes === shepherd.CONNECTION_ERROR_OR_INCOMPLETE_DATA) { verifyMerkleRes === shepherd.CONNECTION_ERROR_OR_INCOMPLETE_DATA) {
@ -141,7 +152,7 @@ module.exports = (shepherd) => {
}); });
}); });
} else { } else {
return new shepherd.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
ecl.connect(); ecl.connect();
ecl.blockchainAddressListunspent(address) ecl.blockchainAddressListunspent(address)
.then((json) => { .then((json) => {

21
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) => { module.exports = (shepherd) => {
// get merkle root // get merkle root
shepherd.getMerkleRoot = (txid, proof, pos) => { 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 hash = txid;
let serialized; let serialized;
@ -46,7 +49,7 @@ module.exports = (shepherd) => {
let ecl = new shepherd.electrumJSCore(_mainServer[1], _mainServer[0], _mainServer[2]); // tcp or tls 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(`main server: ${mainServer}`, true);
shepherd.log(`verification server: ${randomServer}`, 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].server, true);
shepherd.log(shepherd.electrumCoins[coin].serverList, true); shepherd.log(shepherd.electrumCoins[coin].serverList, true);
return new shepherd.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (_serverList !== 'none') { if (_serverList !== 'none') {
let _filteredServerList = []; let _filteredServerList = [];
@ -134,7 +137,11 @@ module.exports = (shepherd) => {
shepherd.get('/electrum/merkle/verify', (req, res, next) => { shepherd.get('/electrum/merkle/verify', (req, res, next) => {
if (shepherd.checkToken(req.query.token)) { 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) => { .then((verifyMerkleRes) => {
const successObj = { const successObj = {
msg: 'success', msg: 'success',

26
routes/shepherd/electrum/transactions.js

@ -1,4 +1,5 @@
const async = require('async'); const async = require('async');
const Promise = require('bluebird');
module.exports = (shepherd) => { module.exports = (shepherd) => {
shepherd.sortTransactions = (transactions, sortBy) => { shepherd.sortTransactions = (transactions, sortBy) => {
@ -16,7 +17,7 @@ module.exports = (shepherd) => {
} }
shepherd.getTransaction = (txid, network, ecl) => { shepherd.getTransaction = (txid, network, ecl) => {
return new shepherd.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!shepherd.electrumCache[network]) { if (!shepherd.electrumCache[network]) {
shepherd.electrumCache[network] = {}; shepherd.electrumCache[network] = {};
} }
@ -40,7 +41,7 @@ module.exports = (shepherd) => {
} }
shepherd.getBlockHeader = (height, network, ecl) => { shepherd.getBlockHeader = (height, network, ecl) => {
return new shepherd.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!shepherd.electrumCache[network]) { if (!shepherd.electrumCache[network]) {
shepherd.electrumCache[network] = {}; shepherd.electrumCache[network] = {};
} }
@ -67,12 +68,15 @@ module.exports = (shepherd) => {
if (shepherd.checkToken(req.query.token)) { if (shepherd.checkToken(req.query.token)) {
const network = req.query.network || shepherd.findNetworkObj(req.query.coin); 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 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); shepherd.log('electrum listtransactions ==>', true);
if (!req.query.full || ecl.insight) { if (!req.query.full ||
ecl.insight) {
ecl.connect(); ecl.connect();
ecl.blockchainAddressGetHistory(req.query.address) ecl.blockchainAddressGetHistory(_address)
.then((json) => { .then((json) => {
ecl.close(); ecl.close();
shepherd.log(json, true); shepherd.log(json, true);
@ -89,14 +93,14 @@ module.exports = (shepherd) => {
} else { } else {
// !expensive call! // !expensive call!
// TODO: limit e.g. 1-10, 10-20 etc // TODO: limit e.g. 1-10, 10-20 etc
const MAX_TX = req.query.maxlength || 10; const MAX_TX = _maxlength || 10;
ecl.connect(); ecl.connect();
ecl.blockchainNumblocksSubscribe() ecl.blockchainNumblocksSubscribe()
.then((currentHeight) => { .then((currentHeight) => {
if (currentHeight && if (currentHeight &&
Number(currentHeight) > 0) { Number(currentHeight) > 0) {
ecl.blockchainAddressGetHistory(req.query.address) ecl.blockchainAddressGetHistory(_address)
.then((json) => { .then((json) => {
if (json && if (json &&
json.length) { json.length) {
@ -108,6 +112,7 @@ module.exports = (shepherd) => {
shepherd.log(json.length, true); shepherd.log(json.length, true);
let index = 0; let index = 0;
// callback hell, use await?
async.eachOfSeries(json, (transaction, ind, callback) => { async.eachOfSeries(json, (transaction, ind, callback) => {
shepherd.getBlockHeader(transaction.height, network, ecl) shepherd.getBlockHeader(transaction.height, network, ecl)
.then((blockInfo) => { .then((blockInfo) => {
@ -130,11 +135,12 @@ module.exports = (shepherd) => {
// shepherd.log(decodedTx.outputs, true); // shepherd.log(decodedTx.outputs, true);
let index2 = 0; let index2 = 0;
if (decodedTx && if (decodedTx &&
decodedTx.inputs && decodedTx.inputs &&
decodedTx.inputs.length) { decodedTx.inputs.length) {
async.eachOfSeries(decodedTx.inputs, (_decodedInput, ind2, callback2) => { async.eachOfSeries(decodedTx.inputs, (_decodedInput, ind2, callback2) => {
function checkLoop() { const checkLoop = () => {
index2++; index2++;
if (index2 === decodedTx.inputs.length) { if (index2 === decodedTx.inputs.length) {
@ -149,7 +155,7 @@ module.exports = (shepherd) => {
confirmations: Number(transaction.height) === 0 ? 0 : currentHeight - transaction.height, 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) { if (formattedTx.type) {
formattedTx.height = transaction.height; formattedTx.height = transaction.height;
@ -223,7 +229,7 @@ module.exports = (shepherd) => {
confirmations: Number(transaction.height) === 0 ? 0 : currentHeight - transaction.height, 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); _rawtx.push(formattedTx);
index++; index++;
@ -251,7 +257,7 @@ module.exports = (shepherd) => {
timestamp: 'cant get block info', timestamp: 'cant get block info',
confirmations: Number(transaction.height) === 0 ? 0 : currentHeight - transaction.height, 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); _rawtx.push(formattedTx);
index++; index++;

2
routes/shepherd/init.js

@ -18,7 +18,7 @@ module.exports = (shepherd) => {
fs.readdir(rootLocation, (err, items) => { fs.readdir(rootLocation, (err, items) => {
for (let i = 0; i < items.length; i++) { for (let i = 0; i < items.length; i++) {
if (items[i].substr(0, 3) === 'gen') { if (items[i].substr(0, 3) === 'gen') {
console.log(items[i]); shepherd.log(`remove items[i]`);
fs.unlinkSync(rootLocation + items[i]); fs.unlinkSync(rootLocation + items[i]);
} }
} }

17
routes/shepherd/log.js

@ -1,3 +1,6 @@
const fs = require('fs-extra');
const Promise = require('bluebird');
module.exports = (shepherd) => { module.exports = (shepherd) => {
shepherd.log = (msg, isSpvOut) => { shepherd.log = (msg, isSpvOut) => {
if (shepherd.appConfig.dev || if (shepherd.appConfig.dev ||
@ -23,14 +26,14 @@ module.exports = (shepherd) => {
const timeFormatted = new Date(Date.now()).toLocaleString('en-US', { hour12: false }); const timeFormatted = new Date(Date.now()).toLocaleString('en-US', { hour12: false });
if (shepherd.appConfig.debug) { if (shepherd.appConfig.debug) {
if (shepherd.fs.existsSync(`${logLocation}/agamalog.txt`)) { if (fs.existsSync(`${logLocation}/agamalog.txt`)) {
shepherd.fs.appendFile(`${logLocation}/agamalog.txt`, `${timeFormatted} ${data}\r\n`, (err) => { fs.appendFile(`${logLocation}/agamalog.txt`, `${timeFormatted} ${data}\r\n`, (err) => {
if (err) { if (err) {
shepherd.log('error writing log file'); shepherd.log('error writing log file');
} }
}); });
} else { } else {
shepherd.fs.writeFile(`${logLocation}/agamalog.txt`, `${timeFormatted} ${data}\r\n`, (err) => { fs.writeFile(`${logLocation}/agamalog.txt`, `${timeFormatted} ${data}\r\n`, (err) => {
if (err) { if (err) {
shepherd.log('error writing log file'); shepherd.log('error writing log file');
} }
@ -58,7 +61,7 @@ module.exports = (shepherd) => {
}); });
shepherd.getAppRuntimeLog = () => { shepherd.getAppRuntimeLog = () => {
return new shepherd.Promise((resolve, reject) => { return new Promise((resolve, reject) => {
resolve(shepherd.appRuntimeLog); 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) { if (err) {
shepherd.writeLog('error writing gui log file'); shepherd.writeLog('error writing gui log file');
} }
@ -118,8 +121,8 @@ module.exports = (shepherd) => {
if (shepherd.checkToken(req.query.token)) { if (shepherd.checkToken(req.query.token)) {
const logExt = req.query.type === 'txt' ? 'txt' : 'json'; const logExt = req.query.type === 'txt' ? 'txt' : 'json';
if (shepherd.fs.existsSync(`${shepherd.agamaDir}/shepherd/agamalog.${logExt}`)) { if (fs.existsSync(`${shepherd.agamaDir}/shepherd/agamalog.${logExt}`)) {
shepherd.fs.readFile(`${shepherd.agamaDir}/shepherd/agamalog.${logExt}`, 'utf8', (err, data) => { fs.readFile(`${shepherd.agamaDir}/shepherd/agamalog.${logExt}`, 'utf8', (err, data) => {
if (err) { if (err) {
const errorObj = { const errorObj = {
msg: 'error', msg: 'error',

1
routes/shepherd/quitDaemon.js

@ -23,6 +23,7 @@ module.exports = (shepherd) => {
const execCliStop = () => { const execCliStop = () => {
let _arg = []; let _arg = [];
if (chain && if (chain &&
!shepherd.nativeCoindList[key.toLowerCase()] && key !== 'CHIPS') { !shepherd.nativeCoindList[key.toLowerCase()] && key !== 'CHIPS') {
_arg.push(`-ac_name=${chain}`); _arg.push(`-ac_name=${chain}`);

11
routes/shepherd/rpc.js

@ -1,5 +1,8 @@
const fs = require('fs-extra'); const fs = require('fs-extra');
const os = require('os'); const os = require('os');
const exec = require('child_process').exec;
const execFile = require('child_process').execFile;
const request = require('request');
module.exports = (shepherd) => { module.exports = (shepherd) => {
shepherd.getConf = (chain) => { shepherd.getConf = (chain) => {
@ -16,8 +19,8 @@ module.exports = (shepherd) => {
} }
if (fs.existsSync(_confLocation)) { if (fs.existsSync(_confLocation)) {
let _port = shepherd.assetChainPorts[chain];
const _rpcConf = fs.readFileSync(_confLocation, 'utf8'); const _rpcConf = fs.readFileSync(_confLocation, 'utf8');
let _port = shepherd.assetChainPorts[chain];
// any coind // any coind
if (shepherd.nativeCoindList[chain.toLowerCase()]) { if (shepherd.nativeCoindList[chain.toLowerCase()]) {
@ -111,7 +114,7 @@ module.exports = (shepherd) => {
_arg = `${_arg} -datadir=${shepherd.appConfig.dataDir + (_chain ? '/' + key : '')}`; _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(`stdout: ${stdout}`);
//shepherd.log(`stderr: ${stderr}`); //shepherd.log(`stderr: ${stderr}`);
@ -265,7 +268,7 @@ module.exports = (shepherd) => {
// send back body on both success and error // send back body on both success and error
// this bit replicates iguana core's behaviour // this bit replicates iguana core's behaviour
shepherd.request(options, (error, response, body) => { request(options, (error, response, body) => {
if (response && if (response &&
response.statusCode && response.statusCode &&
response.statusCode === 200) { response.statusCode === 200) {
@ -299,7 +302,7 @@ module.exports = (shepherd) => {
} }
_arg = _arg.trim().split(' '); _arg = _arg.trim().split(' ');
shepherd.execFile(_coindCliBin, _arg, (error, stdout, stderr) => { execFile(_coindCliBin, _arg, (error, stdout, stderr) => {
shepherd.log(`stdout: ${stdout}`); shepherd.log(`stdout: ${stdout}`);
shepherd.log(`stderr: ${stderr}`); shepherd.log(`stderr: ${stderr}`);

Loading…
Cancel
Save