This commit is contained in:
Josh Harvey 2016-10-10 14:53:01 +01:00
parent c057fe3df8
commit 259b527214
6 changed files with 68 additions and 81 deletions

View file

@ -4,15 +4,14 @@ var http = require('http')
var https = require('https') var https = require('https')
var express = require('express') var express = require('express')
var bodyParser = require('body-parser') var bodyParser = require('body-parser')
var LamassuConfig = require('lamassu-config')
var routes = require('./routes') var routes = require('./routes')
var plugins = require('./plugins') var plugins = require('./plugins')
var logger = require('./logger') var logger = require('./logger')
var configManager = require('./config-manager')
module.exports = function (options) { module.exports = function (options) {
var app = express() var app = express()
var server var server
var lamassuConfig
const psqlUrl = options.postgresql const psqlUrl = options.postgresql
if (!psqlUrl) { if (!psqlUrl) {
@ -20,33 +19,19 @@ module.exports = function (options) {
process.exit(1) process.exit(1)
} }
lamassuConfig = new LamassuConfig(psqlUrl)
const seedPath = options.seedPath || './seeds/seed.txt' const seedPath = options.seedPath || './seeds/seed.txt'
plugins.init(psqlUrl, seedPath) plugins.init(psqlUrl, seedPath)
lamassuConfig.load(function (err, config) { console.log('DEBUG6')
if (err) {
logger.error('Loading config failed')
throw err
}
configManager.load()
.then(config => {
console.log('DEBUG5: %j', config)
plugins.configure(config) plugins.configure(config)
plugins.startPolling() plugins.startPolling()
plugins.startCheckingNotification() plugins.startCheckingNotification()
}) })
lamassuConfig.on('configUpdate', function () {
lamassuConfig.load(function (err, config) {
if (err) {
return logger.error('Error while reloading config')
}
plugins.configure(config)
logger.info('Config reloaded')
})
})
app.use(bodyParser.json()) app.use(bodyParser.json())
var authMiddleware var authMiddleware
@ -64,24 +49,15 @@ module.exports = function (options) {
server = https.createServer(serverOptions, app) server = https.createServer(serverOptions, app)
authMiddleware = function (req, res, next) { authMiddleware = function (req, res, next) {
lamassuConfig.isAuthorized(routes.getDeviceId(req), function (err, next() // TODO: authentication
device) {
if (err) {
res.json({err: 'Internal Server Error'})
return next(err)
}
if (!device) {
res.json(404, {err: 'Not Found'})
return next(new Error('Device is unpaired'))
}
next()
})
} }
} else { } else {
server = http.createServer(app) server = http.createServer(app)
authMiddleware = function (req, res, next) { authMiddleware = function (req, res, next) {
req.device = {} req.device = {}
console.log('DEBUG2')
console.log(req.route)
return next() return next()
} }
} }
@ -96,7 +72,6 @@ module.exports = function (options) {
routes.init({ routes.init({
app: app, app: app,
localApp: localApp, localApp: localApp,
lamassuConfig: lamassuConfig,
plugins: plugins, plugins: plugins,
authMiddleware: authMiddleware, authMiddleware: authMiddleware,
// reloadConfigMiddleware: reloadConfigMiddleware, // reloadConfigMiddleware: reloadConfigMiddleware,

View file

@ -1,8 +1,9 @@
var pgp = require('pg-promise')() var pgp = require('pg-promise')()
var psqlUrl = require('../lib/options').postgres var psqlUrl = require('../lib/options').postgresql
var R = require('ramda') var R = require('ramda')
function connect () { function connect () {
console.log(psqlUrl)
return pgp(psqlUrl) return pgp(psqlUrl)
} }
exports.connect = connect exports.connect = connect
@ -37,8 +38,8 @@ module.exports = {
} }
function matchesValue (crypto, machine, instance) { function matchesValue (crypto, machine, instance) {
instance.fieldScope.crypto === crypto && return instance.fieldLocator.fieldScope.crypto === crypto &&
instance.fieldScope.machine === machine instance.fieldLocator.fieldScope.machine === machine
} }
function permutations (crypto, machine) { function permutations (crypto, machine) {
@ -50,37 +51,43 @@ function permutations (crypto, machine) {
]) ])
} }
function fallbackValue (arr, instances) { function fallbackValue (crypto, machine, instances) {
const crypto = arr[0]
const machine = arr[1]
const notNil = R.pipe(R.isNil, R.not) const notNil = R.pipe(R.isNil, R.not)
const pickValue = (crypto, machine) => R.find(matchesValue, instances) console.log('DEBUG10: %j', instances)
const pickValue = arr => R.find(instance => matchesValue(arr[0], arr[1], instance), instances)
console.log('DEBUG11: %j', permutations(crypto, machine))
console.log('DEBUG14: %j', R.map(pickValue, permutations(crypto, machine)))
return R.find(notNil, R.map(pickValue, permutations(crypto, machine))) return R.find(notNil, R.map(pickValue, permutations(crypto, machine)))
} }
function generalScoped (crypto, machine, config) { function generalScoped (crypto, machine, config) {
const machineScopedCluster = fieldCluster => const scopedValue = (key, instances) =>
[fieldCluster.code, fallbackValue(crypto, machine, fieldCluster.fieldInstances)] [key, fallbackValue(crypto, machine, keyedValues(key, instances))]
const scopedGroups = group => const keyedValues = (key, instances) => R.filter(r => r.fieldLocator.code === key, instances)
[group.code, R.fromPairs(group.fieldClusters.map(machineScopedCluster))] const keys = instances => R.uniq(R.map(r => r.fieldLocator.code, instances))
const scopedGroups = group => {
const instances = group.values
console.log('DEBUG66: %j', keys(instances))
return [group.code, R.fromPairs(keys(instances).map(key => scopedValue(key, instances)))]
}
return R.fromPairs(config.groups.map(scopedGroups)) return R.fromPairs(config.groups.map(scopedGroups))
} }
function machineScoped (machine, config) { function machineScoped (machine, config) {
generalScoped('global', machine, config) return generalScoped('global', machine, config)
} }
function unscoped (config) { function unscoped (config) {
generalScoped('global', 'global', config) return generalScoped('global', 'global', config)
} }
function cryptoScoped (crypto, config) { function cryptoScoped (crypto, config) {
generalScoped(crypto, 'global', config) return generalScoped(crypto, 'global', config)
} }
function scoped (crypto, machine, config) { function scoped (crypto, machine, config) {
generalScoped(crypto, machine, config) return generalScoped(crypto, machine, config)
} }

View file

@ -13,6 +13,7 @@ try {
} catch (err) { } catch (err) {
try { try {
configPath = path.resolve(os.homedir(), '.lamassu', 'lamassu.json') configPath = path.resolve(os.homedir(), '.lamassu', 'lamassu.json')
console.log(configPath)
options = JSON.parse(fs.readFileSync(configPath)) options = JSON.parse(fs.readFileSync(configPath))
} catch (err2) { } catch (err2) {
console.log('Missing configuration file -- exiting.') console.log('Missing configuration file -- exiting.')

View file

@ -11,7 +11,7 @@ const db = require('./postgresql_interface')
const logger = require('./logger') const logger = require('./logger')
const notifier = require('./notifier') const notifier = require('./notifier')
const T = require('./time') const T = require('./time')
const config = require('./config') const configManager = require('./config-manager')
const tradeIntervals = {} const tradeIntervals = {}
@ -166,13 +166,12 @@ function loadOrConfigPlugin (pluginHandle, pluginType, cryptoCode, cfg, accounts
exports.loadOrConfigPlugin = loadOrConfigPlugin exports.loadOrConfigPlugin = loadOrConfigPlugin
// Note: this whole function gets called every time there's a config update // Note: this whole function gets called every time there's a config update
exports.configure = function configure (cfg) { exports.configure = function configure (config) {
if (config.exchanges.settings.lowBalanceMargin < 1) { console.log('DEBUG4: %j', config)
throw new Error('\'settings.lowBalanceMargin\' has to be >= 1')
}
cachedConfig = cfg cachedConfig = config
const accounts = config.loadAccounts()
const accounts = configManager.loadAccounts()
deviceCurrency = config.fiat.fiatCurrency deviceCurrency = config.fiat.fiatCurrency
cryptoCodes = config.crypto.cryptoCurrencies cryptoCodes = config.crypto.cryptoCurrencies
@ -255,8 +254,10 @@ exports.configure = function configure (cfg) {
) )
} }
exports.getConfig = function getConfig () { exports.getConfig = function getConfig (machineId) {
return cachedConfig console.log('DEBUG3: %j', cachedConfig)
console.log('DEBUG55: %j', configManager.machineScoped(machineId, cachedConfig))
return configManager.machineScoped(machineId, cachedConfig)
} }
exports.logEvent = db.recordDeviceEvent exports.logEvent = db.recordDeviceEvent

View file

@ -2,11 +2,11 @@
const BigNumber = require('bignumber.js') const BigNumber = require('bignumber.js')
const logger = require('./logger') const logger = require('./logger')
const configManager = require('./config-manager')
let mock = false let mock = false
let plugins let plugins
let lamassuConfig
module.exports = { module.exports = {
init, init,
@ -56,6 +56,7 @@ function buildBalances () {
} }
function poll (req, res) { function poll (req, res) {
console.log('DEBUG1')
const deviceId = getDeviceId(req) const deviceId = getDeviceId(req)
const deviceTime = getDeviceTime(req) const deviceTime = getDeviceTime(req)
const pid = req.query.pid const pid = req.query.pid
@ -209,22 +210,11 @@ function verifyTx (req, res) {
} }
function pair (req, res) { function pair (req, res) {
const token = req.body.token // const token = req.body.token
const name = req.body.name // const name = req.body.name
lamassuConfig.pair( // TODO: Pair
token, res.json({success: true})
getDeviceId(req),
name,
err => {
if (err) {
logger.error(err)
return res.json({err: err.message})
}
res.json({success: true})
}
)
} }
function phoneCode (req, res) { function phoneCode (req, res) {
@ -323,14 +313,13 @@ function dispense (req, res) {
.catch(err => logger.error(err)) .catch(err => logger.error(err))
} }
function init (localConfig) { function init (opts) {
lamassuConfig = localConfig.lamassuConfig plugins = opts.plugins
plugins = localConfig.plugins mock = opts.mock
mock = localConfig.mock
const authMiddleware = localConfig.authMiddleware const authMiddleware = opts.authMiddleware
const app = localConfig.app const app = opts.app
const localApp = localConfig.localApp const localApp = opts.localApp
app.get('/poll', authMiddleware, poll) app.get('/poll', authMiddleware, poll)
@ -371,6 +360,15 @@ function init (localConfig) {
res.sendStatus(200) res.sendStatus(200)
}) })
localApp.post('/dbChange', (req, res) => {
return configManager.load()
.then(config => {
plugins.configure(config)
logger.info('Config reloaded')
})
.catch(logger.error)
})
return app return app
} }

View file

@ -89,3 +89,8 @@ options: configure per machine; configure per crypto/fiat
currencies now. (passed in on trade -- we assume that we're using machine currency, which may not be true) currencies now. (passed in on trade -- we assume that we're using machine currency, which may not be true)
- consider defining exchange fiat currency in exchange account config, we don't pass in fiat amount, anyway - consider defining exchange fiat currency in exchange account config, we don't pass in fiat amount, anyway
-----------------------------
- convert result to actual value, not record
- default values