Skip to content

Commit

Permalink
Merge branch 'master' into use-mongo-lock-for-tasks
Browse files Browse the repository at this point in the history
  • Loading branch information
sirpy committed Jul 23, 2020
2 parents fc6496b + a8bc87d commit d2f7410
Show file tree
Hide file tree
Showing 10 changed files with 57 additions and 41 deletions.
5 changes: 4 additions & 1 deletion src/imports/logger/ErrorsTransport.js
Expand Up @@ -35,7 +35,10 @@ export default class ErrorsTransport extends Transport {

log(context) {
const { message: generalMessage, userId, ...data } = context
const [errorMessage, errorObj, extra = {}] = context[SPLAT]

// context[SPLAT] could be undefined in case if just one argument passed to the error log
// i.e log.error('some error message')
const [errorMessage, errorObj, extra = {}] = context[SPLAT] || []
const dataToPassIntoLog = { generalMessage, errorMessage, errorObj, ...extra, ...data }
let errorToPassIntoLog = errorObj

Expand Down
30 changes: 19 additions & 11 deletions src/server/blockchain/AdminWallet.js
Expand Up @@ -170,7 +170,7 @@ export class Wallet {
const adminWalletContractBalance = await this.web3.eth.getBalance(adminWalletAddress)
log.info(`AdminWallet contract balance`, { adminWalletContractBalance, adminWalletAddress })
if (adminWalletContractBalance < adminMinBalance * this.addresses.length) {
log.error('AdminWallet contract low funds', {})
log.error('AdminWallet contract low funds')
if (conf.env !== 'test' && conf.env !== 'development') process.exit(-1)
}

Expand Down Expand Up @@ -368,15 +368,23 @@ export class Wallet {
*/
async whitelistUser(address: string, did: string): Promise<TransactionReceipt | boolean> {
const isVerified = await this.isVerified(address)
let tx

if (isVerified) {
return { status: true }
}
const tx: TransactionReceipt = await this.sendTransaction(this.proxyContract.methods.whitelist(address, did)).catch(
e => {
log.error('Error whitelistUser', e.message, e, { address, did })
throw e
}
)

try {
const transaction = this.proxyContract.methods.whitelist(address, did)

tx = await this.sendTransaction(transaction)
} catch (exception) {
const { message } = exception

log.error('Error whitelistUser', message, exception, { address, did })
throw exception
}

log.info('Whitelisted user', { address, did, tx })
return tx
}
Expand Down Expand Up @@ -522,7 +530,7 @@ export class Wallet {
.catch(e => log.error('Failed to estimate gas for tx', e.message, e))) ||
defaultGas

//adminwallet contract might give wrong gas estimates, so if its more than block gas limit reduce it to default
// adminwallet contract might give wrong gas estimates, so if its more than block gas limit reduce it to default
if (gas > 8000000) gas = defaultGas
gasPrice = gasPrice || defaultGasPrice

Expand All @@ -537,7 +545,7 @@ export class Wallet {
}
currentAddress = address
log.debug(`sending tx from: ${address} | nonce: ${nonce}`, { uuid, balance, gas, gasPrice })
return new Promise((res, rej) => {
return await new Promise((res, rej) => {
tx.send({ gas, gasPrice, chainId: this.networkId, nonce, from: address })
.on('transactionHash', h => {
release()
Expand Down Expand Up @@ -683,7 +691,7 @@ export class Wallet {
(await tx
.estimateGas()
.then(gas => gas + 200000) //buffer for proxy contract, reimburseGas?, and low gas unexpected failures
.catch(e => log.error('Failed to estimate gas for tx', { errMessage: e.message, e }))) ||
.catch(e => log.error('Failed to estimate gas for tx', e.message, e))) ||
defaultGas

//adminwallet contract might give wrong gas estimates, so if its more than block gas limit reduce it to default
Expand Down Expand Up @@ -715,7 +723,7 @@ export class Wallet {
})
.on('confirmation', c => onConfirmation && onConfirmation(c))
.on('error', async e => {
log.error('sendTransaction error:', { error: e.message, e, from: address, uuid })
log.error('sendTransaction error:', e.message, e, { from: address, uuid })
if (isNonceError(e)) {
let netNonce = parseInt(await this.mainnetWeb3.eth.getTransactionCount(address))
log.warn('sendTransaciton nonce failure retry', {
Expand Down
8 changes: 4 additions & 4 deletions src/server/blockchain/stakingModelTasks.js
Expand Up @@ -71,7 +71,7 @@ export class StakingModelManager {
//top ropsten wallet
if (moment().diff(this.lastRopstenTopping, 'days') > 0) {
fetch('https://faucet.metamask.io', { method: 'POST', body: AdminWallet.mainnetAddresses[0] }).catch(e => {
this.log.error('failed calling ropsten faucet', e)
this.log.error('failed calling ropsten faucet', e.message, e)
})
this.lastRopstenTopping = moment()
}
Expand Down Expand Up @@ -156,7 +156,7 @@ export class StakingModelManager {
const cronTime = await this.getNextCollectionTime()
//make sure atleast one hour passes in case of an error
if (cronTime.isBefore(moment().add(1, 'hour'))) cronTime.add(1, 'hour')
this.log.error('collecting interest failed.', { e, errMsg: e.message, cronTime })
this.log.error('collecting interest failed.', e.message, e, { cronTime })
return { result: false, cronTime }
}
}
Expand Down Expand Up @@ -321,7 +321,7 @@ class FishingManager {
unfished = unfished.concat(tofish.slice(totalFished))
fishers.push(fisherAccount)
} catch (e) {
this.log.error('Failed fishing chunk', { tofish, error: e.message, e })
this.log.error('Failed fishing chunk', e.message, e, { tofish })
}
}
if (unfished.length > 0) {
Expand All @@ -338,7 +338,7 @@ class FishingManager {
const cronTime = await this.getNextDay()
return { result: true, cronTime, fishers }
} catch (e) {
this.log.error('fishing task failed:', { e, errMsg: e.message })
this.log.error('fishing task failed:', e.message, e)
const cronTime = await this.getNextDay()
if (cronTime.isBefore(moment().add(1, 'hour'))) cronTime.add(1, 'hour')
return { result: true, cronTime }
Expand Down
3 changes: 3 additions & 0 deletions src/server/db/mongo/models/user-private.js
Expand Up @@ -63,6 +63,9 @@ export const UserPrivateSchema = new mongoose.Schema({
mnemonic: {
type: String
},
profilePublickey: {
type: String
},
hanukaBonus: {
type: mongoose.Schema.Types.Mixed,
default: {}
Expand Down
3 changes: 1 addition & 2 deletions src/server/db/mongo/user-privat-provider.js
Expand Up @@ -312,9 +312,8 @@ class UserPrivate {
)
} catch (exception) {
const { message: errMessage } = exception
const logPayload = { e: exception, errMessage, tasksIdentifiers }

logger.error("Couldn't unlock and update delayed tasks", logPayload)
logger.error("Couldn't unlock and update delayed tasks", errMessage, exception, { tasksIdentifiers })
throw exception
}
}
Expand Down
38 changes: 19 additions & 19 deletions src/server/login/login-middleware.js
Expand Up @@ -12,26 +12,26 @@ import Config from '../server.config.js'
import { recoverPublickey } from '../utils/eth'
import requestRateLimiter from '../utils/requestRateLimiter'

// const ExtractJwt = passportJWT.ExtractJwt
// const JwtStrategy = passportJWT.Strategy

const jwtOptions = {}
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken()
jwtOptions.secretOrKey = Config.jwtPassword
// jwtOptions.issuer = 'accounts.examplesoft.com';
// jwtOptions.audience = 'yoursite.net';
const log = logger.child({ from: 'login-middleware' })

const jwtOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: Config.jwtPassword
}

export const strategy = new Strategy(jwtOptions, async (jwtPayload, next) => {
const log = logger.child({ from: 'login-middleware' })
// usually this would be a database call:
let user = await UserDBPrivate.getUser(jwtPayload.loggedInAs)
log.debug('payload received', { jwtPayload, user })
//if user is empty make sure we have something
user = defaults(user, jwtPayload, { identifier: jwtPayload.loggedInAs })
if (get(jwtPayload, 'loggedInAs')) {
next(null, user)
} else {
next(null, false)
const { loggedInAs: identifier } = jwtPayload
let user = false

if (identifier) {
user = await UserDBPrivate.getUser(identifier) // usually this would be a database call

log.debug('payload received', { jwtPayload, user })
// if user is empty make sure we have something
user = defaults(jwtPayload, user, { identifier })
}

next(null, user)
})

const setup = (app: Router) => {
Expand Down Expand Up @@ -158,7 +158,7 @@ const setup = (app: Router) => {
})
)

logger.child({ from: 'login-middleware' }).info('Done setup login middleware.')
log.info('Done setup login middleware.')
}

export default setup
3 changes: 2 additions & 1 deletion src/server/storage/storageAPI.js
Expand Up @@ -74,6 +74,7 @@ const setup = (app: Router, gunPublic: StorageAPI, storage: StorageAPI) => {
torusProvider: userPayload.torusProvider,
email: sha3(email),
mobile: sha3(mobile),
profilePublickey: userRecord.profilePublickey,
isCompleted: userRecord.isCompleted
? userRecord.isCompleted
: {
Expand All @@ -84,7 +85,7 @@ const setup = (app: Router, gunPublic: StorageAPI, storage: StorageAPI) => {
}
})

const userRecordWithPII = { ...userRecord, ...payloadWithoutCreds, inviteCode, email, mobile }
const userRecordWithPII = { ...payloadWithoutCreds, ...userRecord, inviteCode, email, mobile }
const signUpPromises = []

const p1 = storage
Expand Down
4 changes: 3 additions & 1 deletion src/server/verification/__tests__/verificationAPI.js
Expand Up @@ -261,7 +261,9 @@ describe('verificationAPI', () => {
error: helper.duplicateFoundMessage,
enrollmentResult: {
isVerified: false,
isDuplicate: true
isDuplicate: true,
code: 200,
message: 'The search request was processed successfully.'
}
})

Expand Down
2 changes: 1 addition & 1 deletion src/server/verification/processor/EnrollmentSession.js
Expand Up @@ -55,7 +55,7 @@ export default class EnrollmentSession {
result.enrollmentResult = response
}

log.error('Enrollment session failed with exception:', { result, exception })
log.error('Enrollment session failed with exception:', message, exception, { result })

this.onEnrollmentFailed(exception)
} finally {
Expand Down
2 changes: 1 addition & 1 deletion src/server/verification/verificationAPI.js
Expand Up @@ -101,7 +101,7 @@ const setup = (app: Router, verifier: VerificationAPI, gunPublic: StorageAPI, st
res.json({ success: true, sessionToken })
} catch (exception) {
const { message } = exception
log.error('generating enrollment session token failed:', { message, exception, user })
log.error('generating enrollment session token failed:', message, exception, { user })
res.status(400).json({ success: false, error: message })
}
})
Expand Down

0 comments on commit d2f7410

Please sign in to comment.