update to es6

This commit is contained in:
Josh Harvey 2016-06-03 13:09:21 +03:00
parent 759eb92735
commit c32120209d

View file

@ -1,38 +1,38 @@
'use strict' 'use strict'
var BigNumber = require('bignumber.js') const BigNumber = require('bignumber.js')
var logger = require('./logger') const logger = require('./logger')
var mock = false let mock = false
var plugins let plugins
var lamassuConfig let lamassuConfig
module.exports = { module.exports = {
init: init, init,
getFingerprint: getFingerprint getFingerprint
} }
var STALE_TICKER = 3 * 60 * 1000 const STALE_TICKER = 3 * 60 * 1000
var STALE_BALANCE = 3 * 60 * 1000 const STALE_BALANCE = 3 * 60 * 1000
var pids = {} const pids = {}
var reboots = {} const reboots = {}
function buildRates () { function buildRates () {
var cryptoCodes = plugins.getcryptoCodes() const cryptoCodes = plugins.getcryptoCodes()
var config = plugins.getConfig() const config = plugins.getConfig()
var settings = config.exchanges.settings const settings = config.exchanges.settings
var cashInCommission = settings.commission const cashInCommission = settings.commission
var cashOutCommission = settings.fiatCommission || cashInCommission const cashOutCommission = settings.fiatCommission || cashInCommission
var rates = {} const rates = {}
cryptoCodes.forEach(function (cryptoCode) { cryptoCodes.forEach(cryptoCode => {
var _rate = plugins.getDeviceRate(cryptoCode) const _rate = plugins.getDeviceRate(cryptoCode)
if (!_rate) return logger.warn('No rate for ' + cryptoCode + ' yet') if (!_rate) return logger.warn('No rate for ' + cryptoCode + ' yet')
if (Date.now() - _rate.timestamp > STALE_TICKER) return logger.warn('Stale rate for ' + cryptoCode) if (Date.now() - _rate.timestamp > STALE_TICKER) return logger.warn('Stale rate for ' + cryptoCode)
var rate = _rate.rates const rate = _rate.rates
rates[cryptoCode] = { rates[cryptoCode] = {
cashIn: rate.ask.times(cashInCommission), cashIn: rate.ask.times(cashInCommission),
cashOut: rate.bid.div(cashOutCommission) cashOut: rate.bid.div(cashOutCommission)
@ -43,11 +43,11 @@ function buildRates () {
} }
function buildBalances () { function buildBalances () {
var cryptoCodes = plugins.getcryptoCodes() const cryptoCodes = plugins.getcryptoCodes()
var _balances = {} const _balances = {}
cryptoCodes.forEach(function (cryptoCode) { cryptoCodes.forEach(cryptoCode => {
var balanceRec = plugins.fiatBalance(cryptoCode) const balanceRec = plugins.fiatBalance(cryptoCode)
if (!balanceRec) return logger.warn('No balance for ' + cryptoCode + ' yet') if (!balanceRec) return logger.warn('No balance for ' + cryptoCode + ' yet')
if (Date.now() - balanceRec.timestamp > STALE_BALANCE) return logger.warn('Stale balance for ' + cryptoCode) if (Date.now() - balanceRec.timestamp > STALE_BALANCE) return logger.warn('Stale balance for ' + cryptoCode)
_balances[cryptoCode] = balanceRec.balance _balances[cryptoCode] = balanceRec.balance
@ -57,112 +57,112 @@ function buildBalances () {
} }
function poll (req, res) { function poll (req, res) {
var fingerprint = getFingerprint(req) const fingerprint = getFingerprint(req)
var pid = req.query.pid const pid = req.query.pid
pids[fingerprint] = {pid: pid, ts: Date.now()} pids[fingerprint] = {pid, ts: Date.now()}
logger.debug('poll request from: %s', fingerprint) logger.debug('poll request from: %s', fingerprint)
var rates = {} let rates = {}
var balances = {} let balances = {}
rates = buildRates() rates = buildRates()
balances = buildBalances() balances = buildBalances()
var config = plugins.getConfig() const config = plugins.getConfig()
var settings = config.exchanges.settings const settings = config.exchanges.settings
var complianceSettings = settings.compliance const complianceSettings = settings.compliance
plugins.pollQueries(session(req)) plugins.pollQueries(session(req))
.then(results => { .then(results => {
var cartridges = results.cartridges const cartridges = results.cartridges
var reboot = reboots[fingerprint] === pid const reboot = reboots[fingerprint] === pid
var response = { const response = {
err: null, err: null,
locale: config.brain.locale, locale: config.brain.locale,
txLimit: parseInt(complianceSettings.maximum.limit, 10), txLimit: parseInt(complianceSettings.maximum.limit, 10),
idVerificationEnabled: complianceSettings.idVerificationEnabled, idVerificationEnabled: complianceSettings.idVerificationEnabled,
cartridges: cartridges, cartridges,
twoWayMode: !!cartridges, twoWayMode: !!cartridges,
zeroConfLimit: settings.zeroConfLimit, zeroConfLimit: settings.zeroConfLimit,
fiatTxLimit: settings.fiatTxLimit, fiatTxLimit: settings.fiatTxLimit,
reboot: reboot, reboot,
rates: rates, rates,
balances: balances, balances,
coins: settings.coins coins: settings.coins
} }
if (response.idVerificationEnabled) { if (response.idVerificationEnabled) {
response.idVerificationLimit = complianceSettings.idVerificationLimit response.idVerificationLimit = complianceSettings.idVerificationLimit
} }
res.json(response) res.json(response)
}) })
.catch(logger.error) .catch(logger.error)
plugins.recordPing(session(req), req.query) plugins.recordPing(session(req), req.query)
.catch(logger.error) .catch(logger.error)
} }
function trade (req, res) { function trade (req, res) {
var tx = req.body const tx = req.body
tx.cryptoAtoms = new BigNumber(tx.cryptoAtoms) tx.cryptoAtoms = new BigNumber(tx.cryptoAtoms)
plugins.trade(session(req), tx) plugins.trade(session(req), tx)
.then(() => res.status(201).json({})) .then(() => res.status(201).json({}))
.catch(err => { .catch(err => {
logger.error(err) logger.error(err)
res.status(500).json({err: err}) res.status(500).json({err})
}) })
} }
function stateChange (req, res) { function stateChange (req, res) {
plugins.stateChange(session(req), req.body) plugins.stateChange(session(req), req.body)
.then(() => res.json({success: true})) .then(() => res.json({success: true}))
.catch(err => { .catch(err => {
console.error(err) console.error(err)
res.json({success: false}) res.json({success: false})
}) })
} }
function send (req, res) { function send (req, res) {
var tx = req.body const tx = req.body
tx.cryptoAtoms = new BigNumber(tx.cryptoAtoms) tx.cryptoAtoms = new BigNumber(tx.cryptoAtoms)
// TODO: use status.statusCode here after confirming machine compatibility // TODO: use status.statusCode here after confirming machine compatibility
// FIX: (joshm) set txHash to status.txId instead of previous status.txHash which wasn't being set // FIX: (joshm) set txHash to status.txId instead of previous status.txHash which wasn't being set
// Need to clean up txHash vs txId // Need to clean up txHash vs txId
return plugins.sendCoins(session(req), tx) return plugins.sendCoins(session(req), tx)
.then(status => res.json({ .then(status => res.json({
txHash: status && status.txHash, txHash: status && status.txHash,
txId: status && status.txId txId: status && status.txId
})) }))
.catch(err => { .catch(err => {
logger.error(err) logger.error(err)
res.json({ res.json({
err: err.message, err: err.message,
errType: err.name errType: err.name
})
}) })
})
} }
function cashOut (req, res) { function cashOut (req, res) {
logger.info({tx: req.body, cmd: 'cashOut'}) logger.info({tx: req.body, cmd: 'cashOut'})
var tx = req.body const tx = req.body
tx.cryptoAtoms = new BigNumber(tx.cryptoAtoms) tx.cryptoAtoms = new BigNumber(tx.cryptoAtoms)
return plugins.cashOut(session(req), req.body) return plugins.cashOut(session(req), req.body)
.then(cryptoAddress => res.json({bitcoinAddress: cryptoAddress})) .then(cryptoAddress => res.json({bitcoinAddress: cryptoAddress}))
.catch(err => { .catch(err => {
res.json({ res.json({
err: err.message, err: err.message,
errType: err.name errType: err.name
})
logger.error(err)
}) })
logger.error(err)
})
} }
function dispenseAck (req, res) { function dispenseAck (req, res) {
@ -178,7 +178,7 @@ function deviceEvent (req, res) {
function verifyUser (req, res) { function verifyUser (req, res) {
if (mock) return res.json({success: true}) if (mock) return res.json({success: true})
plugins.verifyUser(req.body, function (err, idResult) { plugins.verifyUser(req.body, (err, idResult) => {
if (err) { if (err) {
logger.error(err) logger.error(err)
return res.json({err: 'Verification failed'}) return res.json({err: 'Verification failed'})
@ -191,7 +191,7 @@ function verifyUser (req, res) {
function verifyTx (req, res) { function verifyTx (req, res) {
if (mock) return res.json({success: true}) if (mock) return res.json({success: true})
plugins.verifyTx(req.body, function (err, idResult) { plugins.verifyTx(req.body, (err, idResult) => {
if (err) { if (err) {
logger.error(err) logger.error(err)
return res.json({err: 'Verification failed'}) return res.json({err: 'Verification failed'})
@ -202,14 +202,14 @@ function verifyTx (req, res) {
} }
function pair (req, res) { function pair (req, res) {
var token = req.body.token const token = req.body.token
var name = req.body.name const name = req.body.name
lamassuConfig.pair( lamassuConfig.pair(
token, token,
getFingerprint(req), getFingerprint(req),
name, name,
function (err) { err => {
if (err) { if (err) {
logger.error(err) logger.error(err)
return res.json({err: err.message}) return res.json({err: err.message})
@ -221,74 +221,74 @@ function pair (req, res) {
} }
function phoneCode (req, res) { function phoneCode (req, res) {
var phone = req.body.phone const phone = req.body.phone
logger.debug('Phone code requested for: ' + phone) logger.debug('Phone code requested for: ' + phone)
return plugins.getPhoneCode(phone) return plugins.getPhoneCode(phone)
.then(code => res.json({code: code})) .then(code => res.json({code}))
.catch(err => { .catch(err => {
logger.error(err) logger.error(err)
if (err.name === 'BadNumberError') return res.sendStatus(410) if (err.name === 'BadNumberError') return res.sendStatus(410)
return res.sendStatus(500) return res.sendStatus(500)
}) })
} }
function updatePhone (req, res) { function updatePhone (req, res) {
const notified = req.query.notified === 'true' const notified = req.query.notified === 'true'
return plugins.updatePhone(session(req), req.body, notified) return plugins.updatePhone(session(req), req.body, notified)
.then(r => res.json(r)) .then(r => res.json(r))
.catch(err => { .catch(err => {
logger.error(err) logger.error(err)
res.sendStatus(500) res.sendStatus(500)
}) })
} }
function fetchPhoneTx (req, res) { function fetchPhoneTx (req, res) {
return plugins.fetchPhoneTx(req.query.phone) return plugins.fetchPhoneTx(req.query.phone)
.then(r => res.json(r)) .then(r => res.json(r))
.catch(err => { .catch(err => {
logger.error(err) logger.error(err)
res.sendStatus(500) res.sendStatus(500)
}) })
} }
function registerRedeem (req, res) { function registerRedeem (req, res) {
return plugins.registerRedeem(session(req)) return plugins.registerRedeem(session(req))
.then(() => res.json({success: true})) .then(() => res.json({success: true}))
.catch(err => { .catch(err => {
logger.error(err) logger.error(err)
res.sendStatus(500) res.sendStatus(500)
}) })
} }
function waitForDispense (req, res) { function waitForDispense (req, res) {
logger.debug('waitForDispense') logger.debug('waitForDispense')
return plugins.fetchTx(session(req)) return plugins.fetchTx(session(req))
.then(tx => { .then(tx => {
logger.debug('tx fetched') logger.debug('tx fetched')
logger.debug(tx) logger.debug(tx)
if (!tx) return res.sendStatus(404) if (!tx) return res.sendStatus(404)
if (tx.status === req.query.status) return res.sendStatus(304) if (tx.status === req.query.status) return res.sendStatus(304)
res.json({tx: tx}) res.json({tx})
}) })
.catch(err => { .catch(err => {
logger.error(err) logger.error(err)
res.sendStatus(500) res.sendStatus(500)
}) })
} }
function dispense (req, res) { function dispense (req, res) {
const tx = req.body.tx const tx = req.body.tx
return plugins.requestDispense(tx) return plugins.requestDispense(tx)
.then(r => { .then(r => {
return cacheResponse(req, r) return cacheResponse(req, r)
.then(() => res.json(r)) .then(() => res.json(r))
}) })
.catch(err => { .catch(err => {
logger.error(err) logger.error(err)
res.sendStatus(500) res.sendStatus(500)
}) })
} }
function init (localConfig) { function init (localConfig) {
@ -296,9 +296,9 @@ function init (localConfig) {
plugins = localConfig.plugins plugins = localConfig.plugins
mock = localConfig.mock mock = localConfig.mock
var authMiddleware = localConfig.authMiddleware const authMiddleware = localConfig.authMiddleware
var app = localConfig.app const app = localConfig.app
var localApp = localConfig.localApp const localApp = localConfig.localApp
app.get('/poll', authMiddleware, poll) app.get('/poll', authMiddleware, poll)
@ -320,15 +320,15 @@ function init (localConfig) {
app.get('/await_dispense', authMiddleware, waitForDispense) app.get('/await_dispense', authMiddleware, waitForDispense)
app.post('/dispense', authMiddleware, cachedResponse, dispense) app.post('/dispense', authMiddleware, cachedResponse, dispense)
localApp.get('/pid', function (req, res) { localApp.get('/pid', (req, res) => {
var machineFingerprint = req.query.fingerprint const machineFingerprint = req.query.fingerprint
var pidRec = pids[machineFingerprint] const pidRec = pids[machineFingerprint]
res.json(pidRec) res.json(pidRec)
}) })
localApp.post('/reboot', function (req, res) { localApp.post('/reboot', (req, res) => {
var pid = req.body.pid const pid = req.body.pid
var fingerprint = req.body.fingerprint const fingerprint = req.body.fingerprint
console.log('pid: %s, fingerprint: %s', pid, fingerprint) console.log('pid: %s, fingerprint: %s', pid, fingerprint)
if (!fingerprint || !pid) { if (!fingerprint || !pid) {
@ -357,11 +357,11 @@ function getFingerprint (req) {
function cachedResponse (req, res, next) { function cachedResponse (req, res, next) {
return plugins.cachedResponse(session(req), req.path, req.method) return plugins.cachedResponse(session(req), req.path, req.method)
.then(r => { .then(r => {
if (!r.body) return next() if (!r.body) return next()
if (r.body.pendingRequest) return res.sendStatus(409) if (r.body.pendingRequest) return res.sendStatus(409)
res.json(r.body) res.json(r.body)
}) })
} }
function cacheResponse (req, body) { function cacheResponse (req, body) {