From 20c0a382a3fbe6db8d26c0038ad3c879c9b12eb9 Mon Sep 17 00:00:00 2001 From: joeuhren Date: Wed, 17 Mar 2021 17:54:09 -0600 Subject: [PATCH] Code cleanup -Replace tabs with double-spaces -Betting spacing and lining up of code functions -Add missing semi-colons -Remove extra characters and spaces where applicable -Remove commented-out code fragments -Add missing 2021 date to LICENSE -Small touchups and other misc nitpickings --- LICENSE | 2 +- README.md | 2 +- app.js | 108 ++++++++------ bin/cluster | 25 ++-- bin/instance | 13 +- lib/apis/coindesk.js | 32 +++-- lib/database.js | 271 +++++++++++++++++++---------------- lib/explorer.js | 191 +++++++++++++++---------- lib/jsonrpc.js | 52 ++++--- lib/locale.js | 46 +++--- lib/markets/altmarkets.js | 73 +++++----- lib/markets/bittrex.js | 88 ++++++------ lib/markets/bleutrade.js | 44 +++--- lib/markets/crex.js | 26 ++-- lib/markets/poloniex.js | 66 ++++----- lib/markets/stex.js | 19 ++- lib/markets/yobit.js | 20 +-- lib/node.js | 8 +- lib/nodeapi.js | 43 ++++-- lib/ratelimit.js | 12 +- locale/en.json | 280 ++++++++++++++++++------------------- models/address.js | 9 +- models/addresstx.js | 6 +- models/heavy.js | 8 +- models/markets.js | 6 +- models/masternode.js | 4 +- models/peers.js | 8 +- models/richlist.js | 4 +- models/stats.js | 6 +- models/tx.js | 10 +- public/css/style.scss | 4 +- routes/index.js | 69 ++++----- scripts/benchmark.js | 29 ++-- scripts/create_backup.sh | 44 +++--- scripts/delete_database.sh | 2 +- scripts/forcesync.sh | 6 +- scripts/forcesynclatest.sh | 6 +- scripts/restore_backup.sh | 82 +++++------ scripts/sync.js | 120 +++++++++------- test/explorerSpec.js | 1 + views/block.pug | 2 +- views/layout.pug | 14 +- 42 files changed, 1001 insertions(+), 860 deletions(-) diff --git a/LICENSE b/LICENSE index 2b58d07..d03f7c1 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2019, The Exor Community +Copyright (c) 2019-2021, The Exor Community Copyright (c) 2017, The Chaincoin Community Copyright (c) 2015, Iquidus Technology Copyright (c) 2015, Luke Williams diff --git a/README.md b/README.md index 29d0331..5e31cc7 100644 --- a/README.md +++ b/README.md @@ -323,7 +323,7 @@ The wallet connected to eIquidus must be running with the following flags: ``` -daemon -txindex ``` - + You may either call your coins daemon using this syntax: ``` diff --git a/app.js b/app.js index b83a41a..0a39891 100644 --- a/app.js +++ b/app.js @@ -1,18 +1,17 @@ -var express = require('express') - , path = require('path') - , nodeapi = require('./lib/nodeapi') - , favicon = require('serve-favicon') - , logger = require('morgan') - , cookieParser = require('cookie-parser') - , bodyParser = require('body-parser') - , settings = require('./lib/settings') - , routes = require('./routes/index') - , lib = require('./lib/explorer') - , db = require('./lib/database') - , package_metadata = require('./package.json') - , locale = require('./lib/locale') - , request = require('postman-request'); - +var express = require('express'), + path = require('path'), + nodeapi = require('./lib/nodeapi'), + favicon = require('serve-favicon'), + logger = require('morgan'), + cookieParser = require('cookie-parser'), + bodyParser = require('body-parser'), + settings = require('./lib/settings'), + routes = require('./routes/index'), + lib = require('./lib/explorer'), + db = require('./lib/database'), + package_metadata = require('./package.json'), + locale = require('./lib/locale'), + request = require('postman-request'); var app = express(); var apiAccessList = []; @@ -38,12 +37,12 @@ Object.keys(settings.blockchain_specific).forEach(function(key, index, map) { nodeapi.setAccess('only', apiAccessList); // determine if cors should be enabled if (settings.webserver.cors.enabled == true) { - app.use(function(req, res, next) { - res.header("Access-Control-Allow-Origin", settings.webserver.cors.corsorigin); - res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST'); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - next(); - }); + app.use(function(req, res, next) { + res.header("Access-Control-Allow-Origin", settings.webserver.cors.corsorigin); + res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST'); + res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); + next(); + }); } // view engine setup app.set('views', path.join(__dirname, 'views')); @@ -79,9 +78,9 @@ app.post('/claim', function(req, res) { if (message == req.body.message) { // call the verifymessage api lib.verify_message(req.body.address, req.body.signature, req.body.message, function(body) { - if (body == false) { + if (body == false) res.json({'status': 'failed', 'error': true, 'message': 'Invalid signature'}); - } else if (body == true) { + else if (body == true) { db.update_label(req.body.address, req.body.message, function(val) { // check if the update was successful if (val == '') @@ -120,27 +119,33 @@ app.use('/ext/getaddress/:hash', function(req, res) { db.get_address_txs_ajax(req.params.hash, 0, settings.api_page.public_apis.ext.getaddresstxs.max_items_per_query, function(txs, count) { if (address) { var last_txs = []; + for (i = 0; i < txs.length; i++) { if (typeof txs[i].txid !== "undefined") { var out = 0, - vin = 0, - tx_type = 'vout', - row = {}; + vin = 0, + tx_type = 'vout', + row = {}; + txs[i].vout.forEach(function (r) { if (r.addresses == req.params.hash) out += r.amount; }); + txs[i].vin.forEach(function (s) { if (s.addresses == req.params.hash) vin += s.amount; }); + if (vin > out) tx_type = 'vin'; + row['addresses'] = txs[i].txid; row['type'] = tx_type; last_txs.push(row); } } + var a_ext = { address: address.a_id, sent: (address.sent / 100000000), @@ -148,6 +153,7 @@ app.use('/ext/getaddress/:hash', function(req, res) { balance: (address.balance / 100000000).toString().replace(/(^-+)/mg, ''), last_txs: last_txs }; + res.send(a_ext); } else res.send({ error: 'address not found.', hash: req.params.hash}); @@ -161,13 +167,13 @@ app.use('/ext/gettx/:txid', function(req, res) { // check if the gettx api is enabled if (settings.api_page.enabled == true && settings.api_page.public_apis.ext.gettx.enabled == true) { var txid = req.params.txid; + db.get_tx(txid, function(tx) { if (tx) { lib.get_blockcount(function(blockcount) { res.send({ active: 'tx', tx: tx, confirmations: settings.shared_pages.confirmations, blockcount: (blockcount ? blockcount : 0)}); }); - } - else { + } else { lib.get_rawtransaction(txid, function(rtx) { if (rtx && rtx.txid) { lib.prepare_vin(rtx, function(vin) { @@ -181,8 +187,9 @@ app.use('/ext/gettx/:txid', function(req, res) { total: total.toFixed(8), timestamp: rtx.time, blockhash: '-', - blockindex: -1, + blockindex: -1 }; + res.send({ active: 'tx', tx: utx, confirmations: settings.shared_pages.confirmations, blockcount:-1}); } else { var utx = { @@ -192,8 +199,9 @@ app.use('/ext/gettx/:txid', function(req, res) { total: total.toFixed(8), timestamp: rtx.time, blockhash: rtx.blockhash, - blockindex: rtx.blockheight, + blockindex: rtx.blockheight }; + lib.get_blockcount(function(blockcount) { res.send({ active: 'tx', tx: utx, confirmations: settings.shared_pages.confirmations, blockcount: (blockcount ? blockcount : 0)}); }); @@ -201,9 +209,8 @@ app.use('/ext/gettx/:txid', function(req, res) { }); }); }); - } else { + } else res.send({ error: 'tx not found.', hash: txid}); - } }); } }); @@ -244,7 +251,7 @@ app.use('/ext/getcurrentprice', function(req, res) { if (settings.api_page.enabled == true && settings.api_page.public_apis.ext.getcurrentprice.enabled == true) { db.get_stats(settings.coin.name, function (stats) { eval('var p_ext = { "last_price_' + settings.markets_page.default_exchange.trading_pair.split('/')[1].toLowerCase() + '": stats.last_price, "last_price_usd": stats.last_usd_price, }'); - res.send(p_ext); + res.send(p_ext); }); } else res.end('This method is disabled'); @@ -297,6 +304,7 @@ app.use('/ext/getlasttxs/:min', function(req, res) { if (split.length > 2 && split[2] == 'internal') internal = true; } + break; } @@ -363,11 +371,13 @@ app.use('/ext/getaddresstxs/:address/:start/:length', function(req, res) { if (internal) { var row = []; + row.push(txs[i].timestamp); row.push(txs[i].txid); row.push(Number(out / 100000000)); row.push(Number(vin / 100000000)); row.push(Number(txs[i].balance / 100000000)); + data.push(row); } else { data.push({ @@ -399,6 +409,7 @@ app.use('/ext/getsummary', function(req, res) { if ((settings.api_page.enabled == true && settings.api_page.public_apis.ext.getsummary.enabled == true) || (req.headers['x-requested-with'] != null && req.headers['x-requested-with'].toLowerCase() == 'xmlhttprequest' && req.headers.referer != null && req.headers.accept.indexOf('text/javascript') > -1 && req.headers.accept.indexOf('application/json') > -1)) { lib.get_difficulty(function(difficulty) { difficultyHybrid = ''; + if (difficulty && difficulty['proof-of-work']) { if (settings.shared_pages.difficulty == 'Hybrid') { difficultyHybrid = 'POS: ' + difficulty['proof-of-stake']; @@ -408,6 +419,7 @@ app.use('/ext/getsummary', function(req, res) { else difficulty = difficulty['proof-of-stake']; } + lib.get_hashrate(function(hashrate) { lib.get_connectioncount(function(connections) { lib.get_blockcount(function(blockcount) { @@ -415,6 +427,7 @@ app.use('/ext/getsummary', function(req, res) { lib.get_masternodecount(function(masternodestotal) { if (hashrate == 'There was an error. Check your console.') hashrate = 0; + // check if the masternode count api is enabled if (settings.api_page.public_apis.rpc.getmasternodecount.enabled == true && settings.api_cmds['getmasternodecount'] != null && settings.api_cmds['getmasternodecount'] != '') { // masternode count api is available @@ -424,9 +437,11 @@ app.use('/ext/getsummary', function(req, res) { if (masternodestotal) { if (masternodestotal.total) mn_total = masternodestotal.total; + if (masternodestotal.enabled) mn_enabled = masternodestotal.enabled; } + res.send({ difficulty: (difficulty ? difficulty : '-'), difficultyHybrid: difficultyHybrid, @@ -477,6 +492,7 @@ app.use('/ext/getnetworkpeers', function(req, res) { delete peers[i]['_doc']['_id']; delete peers[i]['_doc']['__v']; } + // check if this is an internal request if (internal) { // display data formatted for internal datatable @@ -501,6 +517,7 @@ app.use('/ext/getmasternodelist', function(req, res) { delete masternodes[i]['_doc']['_id']; delete masternodes[i]['_doc']['__v']; } + // return masternode list res.send(masternodes); }); @@ -524,6 +541,7 @@ app.use('/ext/getmasternoderewards/:hash/:since', function(req, res) { rewards[i]['total'] = rewards[i]['total'] / 100000000; rewards[i]['vout']['amount'] = rewards[i]['vout']['amount'] / 100000000; } + // return list of masternode rewards res.json(rewards); } else @@ -693,7 +711,7 @@ if (settings.shared_pages.page_header.panels.logo_panel.enabled == true && setti panel_order.sort(function(a,b) { return a.val - b.val; }); -for (var i=1; i<6; i++) +for (var i = 1; i < 6; i++) app.set('panel'+i.toString(), ((panel_order.length >= i) ? panel_order[i-1].name : '')); app.set('market_data', market_data); @@ -709,23 +727,23 @@ app.use(function(req, res, next) { // development error handler // will print stacktrace if (app.get('env') === 'development') { - app.use(function(err, req, res, next) { - res.status(err.status || 500); - res.render('error', { - message: err.message, - error: err - }); + app.use(function(err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: err }); + }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { - res.status(err.status || 500); - res.render('error', { - message: err.message, - error: {} - }); + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: {} + }); }); module.exports = app; \ No newline at end of file diff --git a/bin/cluster b/bin/cluster index 6c58169..a452a3f 100644 --- a/bin/cluster +++ b/bin/cluster @@ -7,37 +7,38 @@ if (cluster.isMaster) { console.log('Error: unable to create cluster.pid'); process.exit(1); } else { - console.log('Starting cluster with pid: ' + process.pid); - //ensure workers exit cleanly + console.log('Starting cluster with pid: ' + process.pid); + + // ensure workers exit cleanly process.on('SIGINT', function() { console.log('Cluster shutting down..'); + for (var id in cluster.workers) { console.log('Worker shutting down (' + id + ')'); cluster.workers[id].kill(); } + // exit the master process process.exit(0); }); - // Count the machine's CPUs + // count the machine's CPUs var cpuCount = require('os').cpus().length; - // Create a worker for each CPU - for (var i = 0; i < cpuCount; i += 1) { + // create a worker for each CPU + for (var i = 0; i < cpuCount; i += 1) cluster.fork(); - } - // Listen for dying workers + // listen for dying workers cluster.on('exit', function (worker, code, signal) { - if (worker['process']['exitCode'] === 0) { + if (worker['process']['exitCode'] === 0) console.log('Worker shut down.'); - } else if ((signal != 'SIGINT') && (worker['process']['exitCode'] !== 0) && (worker.exitedAfterDisconnect !== true)) { + else if ((signal != 'SIGINT') && (worker['process']['exitCode'] !== 0) && (worker.exitedAfterDisconnect !== true)) { console.log('Cluster restarting...'); cluster.fork(); } }); } }); -} else { - require('./instance'); -} \ No newline at end of file +} else + require('./instance'); \ No newline at end of file diff --git a/bin/instance b/bin/instance index 6460cdf..97fc894 100644 --- a/bin/instance +++ b/bin/instance @@ -16,9 +16,7 @@ db.connect(dbString, function() { db.check_stats(settings.coin.name, function(exists) { if (exists == false) { console.log('no stats entry found, creating now..'); - db.create_stats(settings.coin.name, function(){ - //console.log('stats entry created successfully.'); - }); + db.create_stats(settings.coin.name, function() {}); } else { db.get_stats(settings.coin.name, function (stats) { app.locals.stats = stats; @@ -56,19 +54,20 @@ db.connect(dbString, function() { }); } - db.check_richlist(settings.coin.name, function(exists){ + db.check_richlist(settings.coin.name, function(exists) { if (exists == false) { console.log('no richlist entry found, creating now..'); db.create_richlist(settings.coin.name, function() {}); } - }); + }); + if (settings.blockchain_specific.heavycoin.enabled == true) { - db.check_heavy(settings.coin.name, function(exists){ + db.check_heavy(settings.coin.name, function(exists) { if (exists == false) { console.log('no heavycoin entry found, creating now..'); db.create_heavy(settings.coin.name, function() {}); } - }); + }); } var server = app.listen(app.get('port'), '::', function() { diff --git a/lib/apis/coindesk.js b/lib/apis/coindesk.js index 86f1c1c..8507a1d 100644 --- a/lib/apis/coindesk.js +++ b/lib/apis/coindesk.js @@ -1,21 +1,23 @@ var request = require('postman-request'); - + function get_usd_value(cb) { - request({ uri: 'https://api.coindesk.com/v1/bpi/currentprice/USD.json', json: true, headers: {'User-Agent': 'eiquidus'} }, function (error, response, body) { - if (error) { - return cb(error, 0); - } else { - return cb(null, body.bpi.USD['rate_float'].toFixed(4)); - } - }); + request({ uri: 'https://api.coindesk.com/v1/bpi/currentprice/USD.json', json: true, headers: {'User-Agent': 'eiquidus'} }, function (error, response, body) { + if (error) + return cb(error, 0); + else + return cb(null, body.bpi.USD['rate_float'].toFixed(4)); + }); } module.exports = { - get_data: function (cb) { - var error = null; - get_usd_value(function (err, last_usd) { - if (err) { error = err; } - return cb(error, last_usd); - }); - } + get_data: function (cb) { + var error = null; + + get_usd_value(function (err, last_usd) { + if (err) + error = err; + + return cb(error, last_usd); + }); + } }; \ No newline at end of file diff --git a/lib/database.js b/lib/database.js index b3dbf00..695b98e 100644 --- a/lib/database.js +++ b/lib/database.js @@ -1,18 +1,18 @@ -var mongoose = require('mongoose') - , Stats = require('../models/stats') - , Markets = require('../models/markets') - , Masternode = require('../models/masternode') - , Address = require('../models/address') - , AddressTx = require('../models/addresstx') - , Tx = require('../models/tx') - , Richlist = require('../models/richlist') - , Peers = require('../models/peers') - , Heavy = require('../models/heavy') - , lib = require('./explorer') - , settings = require('./settings') - , fs = require('fs') - , coindesk = require('./apis/coindesk') - , async = require('async'); +var mongoose = require('mongoose'), + Stats = require('../models/stats'), + Markets = require('../models/markets'), + Masternode = require('../models/masternode'), + Address = require('../models/address'), + AddressTx = require('../models/addresstx'), + Tx = require('../models/tx'), + Richlist = require('../models/richlist'), + Peers = require('../models/peers'), + Heavy = require('../models/heavy'), + lib = require('./explorer'), + settings = require('./settings'), + fs = require('fs'), + coindesk = require('./apis/coindesk'), + async = require('async'); function find_address(hash, caseSensitive, cb) { if (caseSensitive) { @@ -36,21 +36,19 @@ function find_address(hash, caseSensitive, cb) { function find_address_tx(address, hash, cb) { AddressTx.findOne({a_id: address, txid: hash}, function(err, address_tx) { - if(address_tx) { + if (address_tx) return cb(address_tx); - } else { + else return cb(); - } }); } function find_richlist(coin, cb) { Richlist.findOne({coin: coin}, function(err, richlist) { - if(richlist) { + if (richlist) return cb(richlist); - } else { + else return cb(); - } }); } @@ -58,9 +56,10 @@ function update_address(hash, blockheight, txid, amount, type, cb) { var to_sent = false; var to_received = false; var addr_inc = {} - if ( hash == 'coinbase' ) { + + if (hash == 'coinbase') addr_inc.sent = amount; - } else { + else { if (type == 'vin') { addr_inc.sent = amount; addr_inc.balance = -amount; @@ -69,16 +68,17 @@ function update_address(hash, blockheight, txid, amount, type, cb) { addr_inc.balance = amount; } } + Address.findOneAndUpdate({a_id: hash}, { $inc: addr_inc }, { new: true, upsert: true }, function (err, address) { - if (err) { + if (err) return cb(err); - } else { - if ( hash != 'coinbase' ) { + else { + if (hash != 'coinbase') { AddressTx.findOneAndUpdate({a_id: hash, txid: txid}, { $inc: { amount: addr_inc.balance @@ -92,26 +92,23 @@ function update_address(hash, blockheight, txid, amount, type, cb) { new: true, upsert: true }, function (err,addresstx) { - if (err) { + if (err) return cb(err); - } else { + else return cb(); - } }); - } else { + } else return cb(); - } } }); } function find_tx(txid, cb) { Tx.findOne({txid: txid}, function(err, tx) { - if(tx) { + if (tx) return cb(tx); - } else { + else return cb(null); - } }); } @@ -122,12 +119,14 @@ function save_tx(txid, blockheight, cb) { lib.prepare_vout(tx.vout, txid, vin, ((!settings.blockchain_specific.zksnarks.enabled || typeof tx.vjoinsplit === 'undefined' || tx.vjoinsplit == null) ? [] : tx.vjoinsplit), function(vout, nvin) { lib.syncLoop(vin.length, function (loop) { var i = loop.iteration(); + update_address(nvin[i].addresses, blockheight, txid, nvin[i].amount, 'vin', function() { loop.next(); }); }, function() { lib.syncLoop(vout.length, function (subloop) { var t = subloop.iteration(); + if (vout[t].addresses) { update_address(vout[t].addresses, blockheight, txid, vout[t].amount, 'vout', function() { subloop.next(); @@ -143,8 +142,9 @@ function save_tx(txid, blockheight, cb) { total: total.toFixed(8), timestamp: tx.time, blockhash: tx.blockhash, - blockindex: blockheight, + blockindex: blockheight }); + newTx.save(function(err) { if (err) return cb(err, false); @@ -164,6 +164,7 @@ function save_tx(txid, blockheight, cb) { function get_market_data(market, coin_symbol, pair_symbol, cb) { if (fs.existsSync('./lib/markets/' + market + '.js')) { exMarket = require('./markets/' + market); + exMarket.get_data({coin: coin_symbol, exchange: pair_symbol}, function(err, obj) { return cb(err, obj); }); @@ -216,6 +217,7 @@ module.exports = { // ensure that if this address exists in the richlist that it displays the new alias module.exports.get_richlist(settings.coin.name, function(richlist) { var updated = false; + // loop through received addresses for (r = 0; r < richlist.received.length; r++) { // check if this is the correct address @@ -226,6 +228,7 @@ module.exports = { updated = true; } } + // loop through balance addresses for (b = 0; b < richlist.balance.length; b++) { // check if this is the correct address @@ -233,9 +236,10 @@ module.exports = { // update the claim name richlist.balance[b]['name'] = claim_name; // mark as updated - updated = true; + updated = true; } } + // check if the address was updated in the richlist if (updated) { // save the richlist back to collection @@ -263,6 +267,7 @@ module.exports = { // ensure that if this address exists in the masternode that it displays the new alias module.exports.get_masternodes(function(masternodes) { var updated = false; + // loop through masternode addresses for (m = 0; m < masternodes.length; m++) { // check if this is the correct address @@ -273,6 +278,7 @@ module.exports = { updated = true; } } + // check if the address was updated in the masternode list if (updated) { // save the updated masternode back to collection @@ -295,30 +301,31 @@ module.exports = { check_stats: function(coin, cb) { Stats.findOne({coin: coin}, function(err, stats) { - if(stats) { - // collection exists, now check if it is missing the last_usd_price column - Stats.findOne({last_usd_price: {$exists: false}}, function(err, stats) { - if (stats) { - // the last_usd_price needs to be added to the collection - Stats.updateOne({coin: coin}, { - last_usd_price: 0, - }, function() { return cb(null); }); - } - }); - return cb(true); - } else { + if (stats) { + // collection exists, now check if it is missing the last_usd_price column + Stats.findOne({last_usd_price: {$exists: false}}, function(err, stats) { + if (stats) { + // the last_usd_price needs to be added to the collection + Stats.updateOne({coin: coin}, { + last_usd_price: 0 + }, function() { + return cb(null); + }); + } + }); + + return cb(true); + } else return cb(false); - } }); }, get_stats: function(coin, cb) { Stats.findOne({coin: coin}, function(err, stats) { - if(stats) { + if (stats) return cb(stats); - } else { + else return cb(null); - } }); }, @@ -334,20 +341,19 @@ module.exports = { return cb(); } else { console.log("initial stats entry created for %s", coin); - //console.log(newStats); return cb(); } }); }, get_address: function(hash, caseSensitive, cb) { - find_address(hash, caseSensitive, function(address){ + find_address(hash, caseSensitive, function(address) { return cb(address); }); }, get_richlist: function(coin, cb) { - find_richlist(coin, function(richlist){ + find_richlist(coin, function(richlist) { return cb(richlist); }); }, @@ -358,6 +364,7 @@ module.exports = { var total_addresses = 100; // create the burn address array so that we omit burned coins from the rich list var burn_addresses = settings.richlist_page.burned_coins.addresses; + // always omit the private address from the richlist burn_addresses.push("private_tx"); @@ -387,6 +394,7 @@ module.exports = { Address.find({}, 'a_id name balance received').sort({balance: 'desc'}).limit(total_addresses + burn_addresses.length).exec(function(err, addresses) { var return_addresses = []; var burned_balance = 0.0; + // loop through all richlist addresses addresses.forEach(function (address) { // check if this is a burned coin address @@ -398,6 +406,7 @@ module.exports = { return_addresses.push(address); } }); + // update the rich list collection Richlist.updateOne({coin: settings.coin.name}, { balance: return_addresses, @@ -411,24 +420,25 @@ module.exports = { }, get_tx: function(txid, cb) { - find_tx(txid, function(tx){ + find_tx(txid, function(tx) { return cb(tx); }); }, get_txs: function(block, cb) { var txs = []; + lib.syncLoop(block.tx.length, function (loop) { var i = loop.iteration(); - find_tx(block.tx[i], function(tx){ + + find_tx(block.tx[i], function(tx) { if (tx) { txs.push(tx); loop.next(); - } else { + } else loop.next(); - } - }) - }, function(){ + }); + }, function() { return cb(txs); }); }, @@ -440,12 +450,14 @@ module.exports = { for (i = 0; i < txs.length; i++) { if (internal) { var row = []; + row.push(txs[i].blockindex); row.push(txs[i].blockhash); row.push(txs[i].txid); row.push(txs[i].vout.length); row.push((txs[i].total / 100000000)); row.push(txs[i].timestamp); + data.push(row); } else { data.push({ @@ -458,6 +470,7 @@ module.exports = { }); } } + return cb(data, count); }); }, @@ -467,13 +480,12 @@ module.exports = { if (min > 0) { // min is greater than zero which means we must pull record count from the txes collection Tx.find({'total': {$gte: min}}).countDocuments(function(err, count) { - // Get last transactions where there is at least 1 vout + // get last transactions where there is at least 1 vout Tx.find({'total': {$gte: min}, 'vout': { $gte: { $size: 1 }}}).sort({blockindex: -1}).skip(Number(start)).limit(Number(length)).exec(function(err, txs) { - if (err) { + if (err) return cb(err); - } else { + else return cb(txs, count); - } }); }); } else { @@ -481,11 +493,10 @@ module.exports = { Stats.findOne({coin: settings.coin.name}, function(err, stats) { // Get last transactions where there is at least 1 vout Tx.find({'total': {$gte: min}, 'vout': { $gte: { $size: 1 }}}).sort({blockindex: -1}).skip(Number(start)).limit(Number(length)).exec(function(err, txs) { - if (err) { + if (err) return cb(err); - } else { + else return cb(txs, stats.txes); - } }); }); } @@ -493,11 +504,13 @@ module.exports = { get_address_txs_ajax: function(hash, start, length, cb) { var totalCount = 0; - AddressTx.find({a_id: hash}).countDocuments(function(err, count){ - if(err) { + + AddressTx.find({a_id: hash}).countDocuments(function(err, count) { + if (err) return cb(err); - } else { + else { totalCount = count; + AddressTx.aggregate([ { $match: { a_id: hash } }, { $sort: {blockindex: -1} }, @@ -516,21 +529,21 @@ module.exports = { }, { $sort: {blockindex: -1} } ], function (err,balance_sum) { - if (err) { + if (err) return cb(err); - } else { + else { AddressTx.find({a_id: hash}).sort({blockindex: -1}).skip(Number(start)).limit(Number(length)).exec(function (err, address_tx) { - if (err) { + if (err) return cb(err); - } else { + else { var txs = []; var count = address_tx.length; var running_balance = balance_sum.length > 0 ? balance_sum[0].balance : 0; - var txs = []; lib.syncLoop(count, function (loop) { var i = loop.iteration(); + find_tx(address_tx[i].txid, function (tx) { if (tx && !txs.includes(tx)) { tx.balance = running_balance; @@ -539,11 +552,11 @@ module.exports = { } else if (!txs.includes(tx)) { txs.push("1. Not found"); loop.next(); - } else { + } else loop.next(); - } + running_balance = running_balance - address_tx[i].amount; - }) + }); }, function () { return cb(txs, totalCount); }); @@ -559,7 +572,7 @@ module.exports = { var newMarkets = new Markets({ market: market, coin_symbol: coin_symbol, - pair_symbol: pair_symbol, + pair_symbol: pair_symbol }); newMarkets.save(function(err) { @@ -593,15 +606,15 @@ module.exports = { // creates initial richlist entry in database; called on first launch of explorer create_richlist: function(coin, cb) { var newRichlist = new Richlist({ - coin: coin, + coin: coin }); + newRichlist.save(function(err) { if (err) { console.log(err); return cb(); } else { console.log("initial richlist entry created for %s", coin); - //console.log(newRichlist); return cb(); } }); @@ -610,28 +623,28 @@ module.exports = { // drops richlist data for given coin delete_richlist: function(coin, cb) { Richlist.findOneAndRemove({coin: coin}, function(err, exists) { - if(exists) { + if (exists) return cb(true); - } else { + else return cb(false); - } }); }, + // checks richlist data exists for given coin check_richlist: function(coin, cb) { Richlist.findOne({coin: coin}, function(err, exists) { - if(exists) { + if (exists) return cb(true); - } else { + else return cb(false); - } }); }, create_heavy: function(coin, cb) { var newHeavy = new Heavy({ - coin: coin, + coin: coin }); + newHeavy.save(function(err) { if (err) { console.log(err); @@ -645,21 +658,19 @@ module.exports = { check_heavy: function(coin, cb) { Heavy.findOne({coin: coin}, function(err, exists) { - if(exists) { + if (exists) return cb(true); - } else { + else return cb(false); - } }); }, get_heavy: function(coin, cb) { Heavy.findOne({coin: coin}, function(err, heavy) { - if(heavy) { + if (heavy) return cb(heavy); - } else { + else return cb(null); - } }); }, @@ -710,6 +721,7 @@ module.exports = { distribution.t_51_75.total = parseFloat(distribution.t_51_75.total).toFixed(8); distribution.t_76_100.percent = parseFloat(distribution.t_76_100.percent).toFixed(2); distribution.t_76_100.total = parseFloat(distribution.t_76_100.total).toFixed(8); + return cb(distribution); }); }, @@ -729,6 +741,7 @@ module.exports = { lib.get_nextin( function (nextin) { lib.syncLoop(count, function (loop) { var i = loop.iteration(); + lib.get_blockhash(height - i, function (hash) { lib.get_block(hash, function (block) { newVotes.push({ count: height - i, reward: block.reward, vote: (block && block.vote ? block.vote : 0) }); @@ -783,7 +796,7 @@ module.exports = { if (market == settings.markets_page.default_exchange.exchange_name && settings.markets_page.default_exchange.trading_pair.toUpperCase() == coin_symbol.toUpperCase() + '/' + pair_symbol.toUpperCase() && pair_symbol.toUpperCase() == 'BTC') { // this is the default market so update the last price stats Stats.updateOne({coin: settings.coin.name}, { - last_price: obj.stats.last, + last_price: obj.stats.last }, function() { // finished updating market data return cb(null); @@ -813,7 +826,7 @@ module.exports = { Stats.findOne({coin: settings.coin.name}, function(err, stats) { // update the last usd price Stats.updateOne({coin: settings.coin.name}, { - last_usd_price: (last_usd * stats.last_price), + last_usd_price: (last_usd * stats.last_price) }, function() { return cb(null); }); @@ -831,8 +844,10 @@ module.exports = { // check to ensure count is a positive number if (!count || (count != null && typeof count === 'number' && count < 0)) { console.log('Unable to connect to explorer API'); + return cb(false); } + lib.get_supply(function (supply) { lib.get_connectioncount(function (connections) { Stats.findOne({coin: coin}, function(err, stats) { @@ -843,9 +858,9 @@ module.exports = { supply: (supply ? supply : 0), connections: (connections ? connections : 0) }, function(err) { - if (err) { + if (err) console.log("Error during Stats Update: ", err); - } + return cb({ coin: coin, count : count, @@ -870,11 +885,18 @@ module.exports = { var complete = false; var blocks_to_scan = []; var task_limit_blocks = settings.sync.block_parallel_tasks; - if (typeof start === 'undefined' || start < 1) start = 1; // fix for invalid block height (skip genesis block as it should not have valid txs) - if (task_limit_blocks < 1) { task_limit_blocks = 1; } var task_limit_txs = 1; - for (i=start; i<(end+1); i++) + + // fix for invalid block height (skip genesis block as it should not have valid txs) + if (typeof start === 'undefined' || start < 1) + start = 1; + + if (task_limit_blocks < 1) + task_limit_blocks = 1; + + for (i = start; i < (end + 1); i++) blocks_to_scan.push(i); + async.eachLimit(blocks_to_scan, task_limit_blocks, function(block_height, next_block) { if (block_height % settings.sync.save_stats_after_sync_blocks === 0) { Stats.updateOne({coin: coin}, { @@ -882,13 +904,14 @@ module.exports = { txes: txes }, function() {}); } + lib.get_blockhash(block_height, function(blockhash) { if (blockhash) { lib.get_block(blockhash, function(block) { if (block) { async.eachLimit(block.tx, task_limit_txs, function(txid, next_tx) { Tx.findOne({txid: txid}, function(err, tx) { - if(tx) { + if (tx) { setTimeout( function() { tx = null; next_tx(); @@ -902,6 +925,7 @@ module.exports = { if (tx_has_vout) txes++; + setTimeout( function() { tx = null; next_tx(); @@ -918,6 +942,7 @@ module.exports = { }); } else { console.log('block not found: %s', blockhash); + setTimeout( function() { next_block(); }, timeout); @@ -941,28 +966,27 @@ module.exports = { create_peer: function(params, cb) { var newPeer = new Peers(params); + newPeer.save(function(err) { if (err) { console.log(err); return cb(); - } else { + } else return cb(); - } }); }, find_peer: function(address, cb) { Peers.findOne({address: address}, function(err, peer) { - if (err) { + if (err) return cb(null); - } else { - if (peer) { - return cb(peer); - } else { - return cb (null) - } + else { + if (peer) + return cb(peer); + else + return cb (null) } - }) + }); }, drop_peer: function(address, cb) { @@ -970,10 +994,9 @@ module.exports = { if (err) { console.log(err); return cb(); - } else { - return cb () - } - }) + } else + return cb(); + }); }, drop_peers: function(cb) { @@ -981,19 +1004,17 @@ module.exports = { if (err) { console.log(err); return cb(); - } else { - return cb () - } - }) + } else + return cb(); + }); }, get_peers: function(cb) { Peers.find({}, function(err, peers) { - if (err) { + if (err) return cb([]); - } else { + else return cb(peers); - } }); }, @@ -1012,6 +1033,7 @@ module.exports = { // save blank claim name to masternode obejct raw_masternode.claim_name = ''; } + // add/update the masternode module.exports.add_update_masternode(raw_masternode, (masternode == null), function(success) { return cb(success); @@ -1032,6 +1054,7 @@ module.exports = { console.log('Masternode Update - TX or Outidx is missing'); console.log(masternode.txhash); console.log(masternode.outidx); + return cb(false); } else { var mn = new Masternode({ diff --git a/lib/explorer.js b/lib/explorer.js index 1dede55..2c9bb6a 100644 --- a/lib/explorer.js +++ b/lib/explorer.js @@ -1,22 +1,19 @@ -var request = require('postman-request') - , settings = require('./settings') - , Address = require('../models/address'); +var request = require('postman-request'), + settings = require('./settings'), + Address = require('../models/address'); var base_server = 'http://127.0.0.1:' + settings.webserver.port + "/"; - var base_url = base_server + 'api/'; - const onode = require('./node'); const client = new onode.Client(settings.wallet); // returns coinbase total sent as current coin supply function coinbase_supply(cb) { Address.findOne({a_id: 'coinbase'}, function(err, address) { - if (address) { + if (address) return cb(address.sent); - } else { + else return cb(0); - } }); } @@ -38,8 +35,8 @@ function prepareRpcCommand(cmd, addParams) { // Split cmd by spaces var split = cmd.split(' '); - for (i=0; i