diff --git a/lib/cash-in/cash-in-tx.js b/lib/cash-in/cash-in-tx.js
index 2da9f8da..57ea8ccf 100644
--- a/lib/cash-in/cash-in-tx.js
+++ b/lib/cash-in/cash-in-tx.js
@@ -36,8 +36,15 @@ function post (machineTx, pi) {
let addressReuse = false
let walletScore = {}
- return Promise.all([settingsLoader.loadLatest(), checkForBlacklisted(updatedTx), doesTxReuseAddress(updatedTx), getWalletScore(updatedTx, pi)])
- .then(([{ config }, blacklistItems, isReusedAddress, fetchedWalletScore]) => {
+ const promises = [settingsLoader.loadLatest()]
+
+ const isFirstPost = !r.tx.fiat || r.tx.fiat.isZero()
+ if (isFirstPost) {
+ promises.push(checkForBlacklisted(updatedTx), doesTxReuseAddress(updatedTx), getWalletScore(updatedTx, pi))
+ }
+
+ return Promise.all(promises)
+ .then(([{ config }, blacklistItems = false, isReusedAddress = false, fetchedWalletScore = null]) => {
const rejectAddressReuse = configManager.getCompliance(config).rejectAddressReuse
walletScore = fetchedWalletScore
@@ -87,11 +94,7 @@ function logActionById (action, _rec, txId) {
}
function checkForBlacklisted (tx) {
- // Check only on addressScan and avoid testing for blacklist on every bill inserted
- if (!tx.fiat || tx.fiat.isZero()) {
- return blacklist.blocked(tx.toAddress, tx.cryptoCode)
- }
- return Promise.resolve(false)
+ return blacklist.blocked(tx.toAddress, tx.cryptoCode)
}
function postProcess (r, pi, isBlacklisted, addressReuse, walletScore) {
@@ -113,7 +116,7 @@ function postProcess (r, pi, isBlacklisted, addressReuse, walletScore) {
return Promise.resolve({
walletScore: walletScore.score,
operatorCompleted: true,
- error: 'Ciphertrace score is above defined threshold',
+ error: 'Chain analysis score is above defined threshold',
errorCode: 'scoreThresholdReached'
})
}
@@ -167,32 +170,20 @@ function postProcess (r, pi, isBlacklisted, addressReuse, walletScore) {
}
function doesTxReuseAddress (tx) {
- if (!tx.fiat || tx.fiat.isZero()) {
- const sql = `
- SELECT EXISTS (
- SELECT DISTINCT to_address FROM (
- SELECT to_address FROM cash_in_txs WHERE id != $1
- ) AS x WHERE to_address = $2
- )`
- return db.one(sql, [tx.id, tx.toAddress]).then(({ exists }) => exists)
- }
- return Promise.resolve(false)
+ const sql = `
+ SELECT EXISTS (
+ SELECT DISTINCT to_address FROM (
+ SELECT to_address FROM cash_in_txs WHERE id != $1
+ ) AS x WHERE to_address = $2
+ )`
+ return db.one(sql, [tx.id, tx.toAddress]).then(({ exists }) => exists)
}
function getWalletScore (tx, pi) {
return pi.isWalletScoringEnabled(tx)
.then(isEnabled => {
if (!isEnabled) return null
- if (!tx.fiat || tx.fiat.isZero()) {
- return pi.rateWallet(tx.cryptoCode, tx.toAddress)
- }
- // Passthrough the previous result
- return pi.isValidWalletScore(tx.walletScore)
- .then(isValid => ({
- address: tx.toAddress,
- score: tx.walletScore,
- isValid
- }))
+ return pi.rateAddress(tx.cryptoCode, tx.toAddress)
})
}
diff --git a/lib/cash-out/cash-out-tx.js b/lib/cash-out/cash-out-tx.js
index f0437f3c..93274e4d 100644
--- a/lib/cash-out/cash-out-tx.js
+++ b/lib/cash-out/cash-out-tx.js
@@ -117,7 +117,6 @@ function processTxStatus (tx, settings) {
}
function getWalletScore (tx, pi) {
- const rejectEmpty = message => x => _.isNil(x) || _.isEmpty(x) ? Promise.reject(new Error(message)) : x
const statuses = ['published', 'authorized', 'confirmed', 'insufficientFunds']
if (!_.includes(tx.status, statuses) || !_.isNil(tx.walletScore)) {
@@ -128,20 +127,13 @@ function getWalletScore (tx, pi) {
return pi.isWalletScoringEnabled(tx)
.then(isEnabled => {
if (!isEnabled) return tx
- return pi.getTransactionHash(tx)
- .then(rejectEmpty('No transaction hashes'))
- .then(txHashes => pi.getInputAddresses(tx, txHashes))
- .then(rejectEmpty('No input addresses'))
- .then(addresses => Promise.all(_.map(it => pi.rateWallet(tx.cryptoCode, it), addresses)))
- .then(rejectEmpty('No score ratings'))
- .then(_.maxBy(_.get(['score'])))
- .then(highestScore =>
- // Conservatively assign the highest risk of all input addresses to the risk of this transaction
- highestScore.isValid
- ? _.assign(tx, { walletScore: highestScore.score })
+ return pi.rateTransaction(tx)
+ .then(res =>
+ res.isValid
+ ? _.assign(tx, { walletScore: res.score })
: _.assign(tx, {
- walletScore: highestScore.score,
- error: 'Ciphertrace score is above defined threshold',
+ walletScore: res.score,
+ error: 'Chain analysis score is above defined threshold',
errorCode: 'scoreThresholdReached',
dispense: true
})
@@ -149,7 +141,7 @@ function getWalletScore (tx, pi) {
.catch(error => _.assign(tx, {
walletScore: 10,
error: `Failure getting address score: ${error.message}`,
- errorCode: 'ciphertraceError',
+ errorCode: 'walletScoringError',
dispense: true
}))
})
diff --git a/lib/customers.js b/lib/customers.js
index 371e5634..071604cd 100644
--- a/lib/customers.js
+++ b/lib/customers.js
@@ -18,7 +18,7 @@ const sms = require('./sms')
const settingsLoader = require('./new-settings-loader')
const logger = require('./logger')
-const TX_PASSTHROUGH_ERROR_CODES = ['operatorCancel', 'scoreThresholdReached', 'ciphertraceError']
+const TX_PASSTHROUGH_ERROR_CODES = ['operatorCancel', 'scoreThresholdReached', 'walletScoringError']
const ID_PHOTO_CARD_DIR = process.env.ID_PHOTO_CARD_DIR
const FRONT_CAMERA_DIR = process.env.FRONT_CAMERA_DIR
diff --git a/lib/new-admin/config/accounts.js b/lib/new-admin/config/accounts.js
index 36bcee22..0041ba93 100644
--- a/lib/new-admin/config/accounts.js
+++ b/lib/new-admin/config/accounts.js
@@ -59,7 +59,7 @@ const ALL_ACCOUNTS = [
{ code: 'none', display: 'None', class: ZERO_CONF, cryptos: ALL_CRYPTOS },
{ code: 'blockcypher', display: 'Blockcypher', class: ZERO_CONF, cryptos: [BTC] },
{ code: 'mock-zero-conf', display: 'Mock 0-conf', class: ZERO_CONF, cryptos: ALL_CRYPTOS, dev: true },
- { code: 'ciphertrace', display: 'CipherTrace', class: WALLET_SCORING, cryptos: [BTC, ETH, LTC, BCH] },
+ { code: 'scorechain', display: 'Scorechain', class: WALLET_SCORING, cryptos: [BTC, ETH, LTC, BCH, DASH, USDT, USDT_TRON, TRX] },
{ code: 'mock-scoring', display: 'Mock scoring', class: WALLET_SCORING, cryptos: ALL_CRYPTOS, dev: true }
]
diff --git a/lib/plugins.js b/lib/plugins.js
index 18aaee5f..fe6b5b79 100644
--- a/lib/plugins.js
+++ b/lib/plugins.js
@@ -994,20 +994,8 @@ function plugins (settings, deviceId) {
.then(buildRates)
}
- function rateWallet (cryptoCode, address) {
- return walletScoring.rateWallet(settings, cryptoCode, address)
- }
-
- function isValidWalletScore (score) {
- return walletScoring.isValidWalletScore(settings, score)
- }
-
- function getTransactionHash (tx) {
- return walletScoring.getTransactionHash(settings, tx.cryptoCode, tx.toAddress)
- }
-
- function getInputAddresses (tx, txHashes) {
- return walletScoring.getInputAddresses(settings, tx.cryptoCode, txHashes)
+ function rateAddress (cryptoCode, address) {
+ return walletScoring.rateAddress(settings, cryptoCode, address)
}
function isWalletScoringEnabled (tx) {
@@ -1046,10 +1034,7 @@ function plugins (settings, deviceId) {
notifyOperator,
fetchCurrentConfigVersion,
pruneMachinesHeartbeat,
- rateWallet,
- isValidWalletScore,
- getTransactionHash,
- getInputAddresses,
+ rateAddress,
isWalletScoringEnabled,
probeLN,
buildAvailableUnits
diff --git a/lib/plugins/wallet-scoring/ciphertrace/ciphertrace.js b/lib/plugins/wallet-scoring/ciphertrace/ciphertrace.js
deleted file mode 100644
index d3922525..00000000
--- a/lib/plugins/wallet-scoring/ciphertrace/ciphertrace.js
+++ /dev/null
@@ -1,150 +0,0 @@
-const coins = require('@lamassu/coins')
-const axios = require('axios')
-const _ = require('lodash/fp')
-
-const logger = require('../../../logger')
-
-const NAME = 'CipherTrace'
-const SUPPORTED_COINS = ['BTC', 'ETH', 'BCH', 'LTC']
-
-function getClient (account) {
- if (_.isNil(account) || !account.enabled) return null
-
- const [ctv1, username, secretKey] = account.authorizationValue.split(':')
- if (_.isNil(ctv1) || _.isNil(username) || _.isNil(secretKey)) {
- throw new Error('Invalid CipherTrace configuration')
- }
-
- const apiVersion = ctv1.slice(-2)
- const authHeader = {
- 'Authorization': account.authorizationValue
- }
- return { apiVersion, authHeader }
-}
-
-function rateWallet (account, cryptoCode, address) {
- const client = getClient(account)
- if (!_.includes(_.toUpper(cryptoCode), SUPPORTED_COINS) || _.isNil(client)) return Promise.resolve(null)
-
- const { apiVersion, authHeader } = client
- const threshold = account.scoreThreshold
-
- logger.info(`** DEBUG ** rateWallet ENDPOINT: https://rest.ciphertrace.com/aml/${apiVersion}/${_.toLower(cryptoCode)}/risk?address=${address}`)
-
- return axios.get(`https://rest.ciphertrace.com/aml/${apiVersion}/${_.toLower(cryptoCode)}/risk?address=${address}`, {
- headers: authHeader
- })
- .then(res => ({ address, score: res.data.risk, isValid: res.data.risk < threshold }))
- .then(result => {
- logger.info(`** DEBUG ** rateWallet RETURN: ${result}`)
- return result
- })
- .catch(err => {
- logger.error(`** DEBUG ** rateWallet ERROR: ${err.message}`)
- throw err
- })
-}
-
-function isValidWalletScore (account, score) {
- const client = getClient(account)
- if (_.isNil(client)) return Promise.resolve(true)
-
- const threshold = account.scoreThreshold
- return _.isNil(account) ? Promise.resolve(true) : Promise.resolve(score < threshold)
-}
-
-function getAddressTransactionsHashes (receivingAddress, cryptoCode, client, wallet) {
- const { apiVersion, authHeader } = client
-
- logger.info(`** DEBUG ** getTransactionHash ENDPOINT: https://rest.ciphertrace.com/api/${apiVersion}/${_.toLower(cryptoCode) !== 'btc' ? `${_.toLower(cryptoCode)}_` : ``}address/search?features=tx&address=${receivingAddress}&mempool=true`)
-
- return axios.get(`https://rest.ciphertrace.com/api/${apiVersion}/${_.toLower(cryptoCode) !== 'btc' ? `${_.toLower(cryptoCode)}_` : ``}address/search?features=tx&address=${receivingAddress}&mempool=true`, {
- headers: authHeader
- })
- .then(_.flow(
- _.get(['data', 'txHistory']),
- _.map(_.get(['txHash']))
- ))
- .catch(err => {
- logger.error(`** DEBUG ** getTransactionHash ERROR: ${err}`)
- logger.error(`** DEBUG ** Fetching transactions hashes via wallet node...`)
- return wallet.getTxHashesByAddress(cryptoCode, receivingAddress)
- })
-}
-
-function getTransactionHash (account, cryptoCode, receivingAddress, wallet) {
- const client = getClient(account)
- if (!_.includes(_.toUpper(cryptoCode), SUPPORTED_COINS) || _.isNil(client)) return Promise.resolve(null)
- return getAddressTransactionsHashes(receivingAddress, cryptoCode, client, wallet)
- .then(txHashes => {
- if (_.size(txHashes) > 1) {
- logger.warn('An address generated by this wallet was used in more than one transaction')
- }
- logger.info('** DEBUG ** getTransactionHash RETURN: ', _.join(', ', txHashes))
- return txHashes
- })
- .catch(err => {
- logger.error('** DEBUG ** getTransactionHash from wallet node ERROR: ', err)
- throw err
- })
-}
-
-function getInputAddresses (account, cryptoCode, txHashes) {
- const client = getClient(account)
- if (_.isEmpty(txHashes) || !_.includes(_.toUpper(cryptoCode), SUPPORTED_COINS) || _.isNil(client))
- return Promise.resolve([])
-
- /* NOTE: The API accepts at most 10 hashes, and for us here more than 1 is already an exception, not the norm. */
- if (_.size(txHashes) > 10)
- return Promise.reject(new Error("Too many tx hashes -- shouldn't happen!"))
-
- const { apiVersion, authHeader } = client
-
- cryptoCode = _.toLower(cryptoCode)
- const lastPathComp = cryptoCode !== 'btc' ? cryptoCode + '_tx' : 'tx'
-
- txHashes = _(txHashes).take(10).join(',')
-
- const url = `https://rest.ciphertrace.com/api/${apiVersion}/${lastPathComp}?txhashes=${txHashes}`
- console.log('** DEBUG ** getInputAddresses ENDPOINT: ', url)
-
- return axios.get(url, { headers: authHeader })
- .then(res => {
- const data = res.data
- if (_.size(data.transactions) > 1) {
- logger.warn('An address generated by this wallet was used in more than one transaction')
- }
-
- const transactionInputs = _.flatMap(it => it.inputs, data.transactions)
- const inputAddresses = _.map(it => it.address, transactionInputs)
-
- logger.info(`** DEBUG ** getInputAddresses RETURN: ${inputAddresses}`)
-
- return inputAddresses
- })
- .catch(err => {
- logger.error(`** DEBUG ** getInputAddresses ERROR: ${err.message}`)
- throw err
- })
-}
-
-function isWalletScoringEnabled (account, cryptoCode) {
- const isAccountEnabled = !_.isNil(account) && account.enabled
-
- if (!isAccountEnabled) return Promise.resolve(false)
-
- if (!SUPPORTED_COINS.includes(cryptoCode) && !coins.utils.isErc20Token(cryptoCode)) {
- return Promise.reject(new Error('Unsupported crypto: ' + cryptoCode))
- }
-
- return Promise.resolve(true)
-}
-
-module.exports = {
- NAME,
- rateWallet,
- isValidWalletScore,
- getTransactionHash,
- getInputAddresses,
- isWalletScoringEnabled
-}
diff --git a/lib/plugins/wallet-scoring/mock-scoring/mock-scoring.js b/lib/plugins/wallet-scoring/mock-scoring/mock-scoring.js
index 455ff4bf..0f154ffc 100644
--- a/lib/plugins/wallet-scoring/mock-scoring/mock-scoring.js
+++ b/lib/plugins/wallet-scoring/mock-scoring/mock-scoring.js
@@ -2,7 +2,7 @@ const NAME = 'FakeScoring'
const { WALLET_SCORE_THRESHOLD } = require('../../../constants')
-function rateWallet (account, cryptoCode, address) {
+function rateAddress (account, cryptoCode, address) {
return new Promise((resolve, _) => {
setTimeout(() => {
console.log('[WALLET-SCORING] DEBUG: Mock scoring rating wallet address %s', address)
@@ -12,30 +12,6 @@ function rateWallet (account, cryptoCode, address) {
})
}
-function isValidWalletScore (account, score) {
- return new Promise((resolve, _) => {
- setTimeout(() => {
- return resolve(score < WALLET_SCORE_THRESHOLD)
- }, 100)
- })
-}
-
-function getTransactionHash (account, cryptoCode, receivingAddress) {
- return new Promise((resolve, _) => {
- setTimeout(() => {
- return resolve('