Compare commits

...
Author SHA1 Message Date
Chris Troutner 3c00ce6644 Merge pull request #96 from Permissionless-Software-Foundation/ct-unstable
fix(error): Removing confusing non-error error
2025-06-06 11:48:14 -07:00
Chris Troutner e9d1b763fd fix(error): Removing confusing non-error error 2025-06-06 11:46:43 -07:00
Chris Troutner 98b5e300c0 Merge pull request #95 from Permissionless-Software-Foundation/ct-unstable
Using User wallet to create and settle Orders, not app wallet.
2025-06-01 18:49:24 -07:00
Chris Troutner 2ea062ae2b Removing e2e tests from unit tests 2025-06-01 18:47:15 -07:00
Chris Troutner c6e5eb9dc9 Updating package-lock 2025-06-01 18:42:16 -07:00
Chris Troutner 46a19b0fb1 linting 2025-06-01 18:34:14 -07:00
Chris Troutner 40cf8cc8de got tests passing again 2025-06-01 18:34:01 -07:00
Chris Troutner ddc70d6fbc feat(completeTx()): Uses user wallet to complete sale 2025-06-01 18:18:34 -07:00
Chris Troutner 625b8895b0 feat(moveTokensFromCustomWallet()): Using user wallet, not system wallet to stash new Offer UTXOs 2025-06-01 17:23:35 -07:00
Chris Troutner 5fd8d8fcd1 Adding llm-bch-dex.md for AI consuption 2025-06-01 16:18:04 -07:00
Chris Troutner 153ebc204a Merge pull request #94 from Permissionless-Software-Foundation/ct-unstable
feat(NOSTR_TOPIC): Changing default nostr topic
2025-05-19 15:40:19 -07:00
Chris Troutner 589c16550c Merge branch 'master' into ct-unstable 2025-05-19 15:37:01 -07:00
Chris Troutner 49063456b6 feat(NOSTR_TOPIC): Changing default nostr topic 2025-05-19 15:34:36 -07:00
Chris Troutner 87eb804cd1 Merge pull request #93 from Permissionless-Software-Foundation/ct-unstable
fix(util): Adding scripts for creating new users
2025-05-19 13:49:31 -07:00
Chris Troutner 23d5118b52 fix(util): Adding scripts for creating new users 2025-05-19 13:48:15 -07:00
Chris Troutner 94eb342435 Merge pull request #92 from Permissionless-Software-Foundation/ct-unstable
Syncing admin settings with upstream ipfs-service-provider
2025-05-19 13:18:38 -07:00
Chris Troutner ac326b8e34 fix(adapter/admin.js): Adding mnemonic for user 2025-05-19 13:16:32 -07:00
Chris Troutner 164a38ad20 linting 2025-05-19 13:11:23 -07:00
Chris Troutner 3300e0fc80 fix(config): Fixing merge conflict in common.js 2025-05-19 13:11:13 -07:00
Chris Troutner 3a4569c33f Merge pull request #175 from Permissionless-Software-Foundation/dh-env-var-admin
feat(admin): added env var setting so only admin can create new users
2025-05-19 13:06:40 -07:00
Daniel Gonzalez 05a0620663 feat(admin): added env var setting so only admin can create new users 2025-05-19 12:17:09 -04:00
Chris Troutner af83c06b43 Merge pull request #174 from Permissionless-Software-Foundation/ct-unstable
fix(usage): Debugging issue with usage tracking
2025-05-18 15:37:46 -07:00
Chris Troutner e6317c3282 fix(usage): Debugging issue with usage tracking 2025-05-18 15:36:32 -07:00
Chris Troutner ddce40bb52 Merge pull request #91 from Permissionless-Software-Foundation/ct-unstable
Production improvements
2025-05-16 07:54:30 -07:00
Chris Troutner 746f9a3488 fix(production): Adding script to get users in prod env 2025-05-16 07:52:58 -07:00
Chris Troutner a611580f48 Turning off CI option 2025-05-15 19:18:41 -07:00
Chris Troutner 07c671ede4 fix(production): Using v3 UI 2025-05-15 17:58:29 -07:00
Chris Troutner 7c8d73810d linting 2025-05-15 07:43:24 -07:00
Chris Troutner 9829e8581c Adding sweep-funds2 script 2025-05-15 07:43:13 -07:00
Chris Troutner a12aa5609d Merge pull request #90 from Permissionless-Software-Foundation/dh-refactor-counteroffer
feat(order): refactored acceptCounterOffer()
2025-05-15 06:01:47 -07:00
25 changed files with 27234 additions and 232 deletions
+7 -1
View File
@@ -183,5 +183,11 @@ export default {
// Nostr
nostrRelay: process.env.NOSTR_RELAY ? process.env.NOSTR_RELAY : 'wss://nostr-relay.psfoundation.info',
nostrTopic: process.env.NOSTR_TOPIC ? process.env.NOSTR_TOPIC : 'bch-dex-test-topic-01'
nostrTopic: process.env.NOSTR_TOPIC ? process.env.NOSTR_TOPIC : 'bch-dex-test-topic-02',
// Account Configuration
disableNewAccounts: process.env.DISABLE_NEW_ACCOUNTS ? true : false,
// Admin password
adminPassword: process.env.ADMIN_PASSWORD
}
+26701
View File
File diff suppressed because it is too large Load Diff
-14
View File
@@ -9861,20 +9861,6 @@
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
"license": "ISC"
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "http://94.130.170.209:4873/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "http://94.130.170.209:4873/function-bind/-/function-bind-1.1.2.tgz",
+2 -2
View File
@@ -6,9 +6,9 @@
"type": "module",
"scripts": {
"start": "node index.js",
"test": "npm run test:all",
"test": "npm run test:unit",
"test:all": "export BCH_DEX=test && c8 --reporter=text mocha --exit --timeout 15000 --recursive test/unit test/e2e/automated/",
"test:unit": "export BCH_DEX=test && mocha --exit --timeout 15000 --recursive test/unit/",
"test:unit": "export BCH_DEX=test && c8 --reporter=text mocha --exit --timeout 15000 --recursive test/unit/",
"test:e2e:auto": "export BCH_DEX=test && mocha --exit --timeout 30000 test/e2e/automated/",
"test:integration": "export BCH_DEX=test && mocha --exit --timeout 45000 --recursive test/integration",
"test:temp": "export BCH_DEX=test && mocha --exit --timeout 15000 -g '#rate-limit' test/unit/json-rpc/",
+4 -4
View File
@@ -46,11 +46,11 @@ WORKDIR /home/safeuser
# Clone the rest.bitcoin.com repository
WORKDIR /home/safeuser
RUN git clone https://github.com/Permissionless-Software-Foundation/bch-dex-ui-v2
RUN git clone https://github.com/Permissionless-Software-Foundation/bch-dex-ui-v3
# Switch to the desired branch. `master` is usually stable,
# and `stage` has the most up-to-date changes.
WORKDIR /home/safeuser/bch-dex-ui-v2
WORKDIR /home/safeuser/bch-dex-ui-v3
# For development: switch to unstable branch
RUN git checkout ct-unstable
@@ -61,13 +61,13 @@ RUN git checkout ct-unstable
RUN npm install
# Build the site
RUN CI=true npm run build
RUN npm run build
# Load the NGINX image.
FROM nginx
EXPOSE 80
# Copy the files built in the first container to the new NGINX container.
COPY --from=builder /home/safeuser/bch-dex-ui-v2/build /usr/share/nginx/html
COPY --from=builder /home/safeuser/bch-dex-ui-v3/build /usr/share/nginx/html
#USER safeuser
+27 -58
View File
@@ -51,70 +51,38 @@ class Admin {
// used by the Listing Manager and test scripts, in order access private API
// functions.
async createSystemUser () {
// Create the system user.
try {
context.password = _this._randomString(20)
const options = {
method: 'POST',
url: `${LOCALHOST}/users`,
data: {
user: {
email: 'system@system.com',
password: context.password,
name: 'admin'
}
}
const context = {
email: 'system@system.com',
name: 'admin',
password: _this.config.adminPassword || _this._randomString(20),
type: 'admin',
mnemonic: 'spread ivory oval pioneer flash gap merit nerve simple image entire trouble'
}
const result = await _this.axios.request(options)
// console.log('admin.data: ', result.data)
// Check if the user already exists
let adminUser = await _this.User.findOne({ email: context.email })
context.email = result.data.user.email
context.id = result.data.user._id
context.token = result.data.token
if (adminUser) {
// Update the password
adminUser.password = context.password
} else {
// Create a new admin user
adminUser = new _this.User(context)
}
// Update context with the new user id and token
context.id = adminUser._id
context.token = await adminUser.generateToken()
// Get the mongoDB entry
const user = await _this.User.findById(context.id)
// Save the user
await adminUser.save()
// Change the user type to admin
user.type = 'admin'
// console.log(`user created: ${JSON.stringify(user, null, 2)}`)
// Save the user model.
await user.save()
// console.log(`admin user created: ${JSON.stringify(result.body, null, 2)}`)
// console.log(`with password: ${context.password}`)
// Write out the system user information to a JSON file that external
// applications like the Task Manager and the test scripts can access.
await jsonFiles.writeJSON(context, JSON_PATH)
// console.log('context: ', context)
// console.log('JSON_PATH: ', JSON_PATH)
// Write the user data to the JSON file
await _this.jsonFiles.writeJSON(context, JSON_PATH)
return context
} catch (err) {
// Handle existing system user.
if (err.response.status === 422) {
try {
// Delete the existing user
await _this.deleteExistingSystemUser()
// Call this function again.
return _this.createSystemUser()
} catch (err2) {
console.error(
'Error in admin.js/createSystemUser() while trying generate new system user.'
)
// process.end(1)
throw err2
}
} else {
console.log('Error in admin.js/createSystemUser: ')
// process.end(1)
throw err
}
} catch (error) {
console.log('Error in admin.js/createSystemUser()')
throw error
}
}
@@ -129,6 +97,7 @@ class Admin {
})
await _this.User.deleteOne({ email: 'system@system.com' })
return true
} catch (err) {
console.log('Error in admin.js/deleteExistingSystemUser()')
throw err
@@ -152,7 +121,7 @@ class Admin {
Accept: 'application/json'
},
data: {
email: 'system@system.com',
email: existingUser.email,
password: existingUser.password
}
}
+3 -1
View File
@@ -41,7 +41,9 @@ const Order = new mongoose.Schema({
nostrEventId: { type: String, required: true }, // Nostr Event Id.
// Additional properties found in createOrder
dataType: { type: String, required: true }
dataType: { type: String, required: true },
userId: { type: String, required: true }
})
export default mongoose.model('order', Order)
+22 -7
View File
@@ -161,10 +161,9 @@ class WalletAdapter {
}
}
// Note: This method uses the system wallet, not the user or admin wallet.
// This method returns an object that contains a private key WIF, public address,
// and the index of the HD wallet that the key pair was generated from.
// TODO: Allow input integer. If input is used, use that as the index. If no
// input is provided, then call incrementNextAddress().
async getKeyPair (hdIndex = 0) {
try {
if (!hdIndex) {
@@ -173,6 +172,7 @@ class WalletAdapter {
}
const mnemonic = this.bchWallet.walletInfo.mnemonic
console.log(`getKeyPair() for HD index: ${hdIndex} called on mnemonic: ${mnemonic}`)
// root seed buffer
const rootSeed = await this.bchWallet.bchjs.Mnemonic.toSeed(mnemonic)
@@ -465,7 +465,7 @@ class WalletAdapter {
// Complete the partially signed transaction by signing the first input,
// then broadcasting the transaction to the network.
async completeTx (hex, hdIndex) {
async completeTx (hex, hdIndex, mnemonic) {
try {
// Input validation
if (!hex || typeof hex !== 'string') {
@@ -474,10 +474,17 @@ class WalletAdapter {
if (typeof hdIndex !== 'number' || hdIndex < 0) {
throw new Error('hdIndex must be a non-negative number!')
}
if (!mnemonic || typeof mnemonic !== 'string') {
throw new Error('mnemonic must be a string!')
}
// console.log('hex: ', hex)
console.log('completeTx() hdIndex: ', hdIndex)
console.log('completeTx() mnemonic: ', mnemonic)
const bchjs = this.bchWallet.bchjs
// Instantiate the user wallet
const userWallet = await this.instanceWallet({ mnemonic })
const bchjs = userWallet.bchjs
// instance of transaction builder
// const transactionBuilder = new bchjs.TransactionBuilder()
@@ -500,10 +507,10 @@ class WalletAdapter {
// 'mainnet'
// )
console.log('completeTx() this.walletInfo: ', this.walletInfo)
console.log('completeTx() userWallet.walletInfo: ', userWallet.walletInfo)
// Get the keypair for the address used in the Order
const keyPair = await this.getKeyPair(hdIndex)
const keyPair = await userWallet.getKeyPair(hdIndex)
console.log(`maker keyPair: ${JSON.stringify(keyPair, null, 2)}`)
const makerECPair = bchjs.ECPair.fromWIF(keyPair.wif)
@@ -587,6 +594,8 @@ class WalletAdapter {
}
}
// This function is consumed by the use-cases/order.js/createOrder() function.
// Tokens are moved from the primary address to a holding address to protect the Order UTXO.
async moveTokensFromCustomWallet (inObj = {}) {
try {
const { tokenId, qty, wallet } = inObj
@@ -601,7 +610,13 @@ class WalletAdapter {
throw new Error('wallet is required!')
}
const keyPair = await this.getKeyPair()
// Replace the system wallet with the user wallet.
// this.bchWallet = wallet
// DEV Note: Storing all token Offers in index 2 of the HD wallet.
// This makes them easy to sweep, and can be uniquely identified by their UTXO.
// Note: use walle.getKeyPair() to use the user wallet. this.getKeyPair uses the system wallet.
const keyPair = await wallet.getKeyPair(2)
console.log('keyPair: ', keyPair)
const receiver = {
+14 -3
View File
@@ -10,6 +10,8 @@ import UserRESTControllerLib from './controller.js'
import Validators from '../middleware/validators.js'
import config from '../../../../config/index.js'
let _this
class UserRouter {
@@ -34,6 +36,7 @@ class UserRouter {
}
// Encapsulate dependencies.
this.config = config
this.userRESTController = new UserRESTControllerLib(dependencies)
this.validators = new Validators()
@@ -52,7 +55,7 @@ class UserRouter {
}
// Define the routes and attach the controller.
this.router.post('/', this.userRESTController.createUser)
this.router.post('/', this.createUser)
this.router.get('/', this.getAll)
this.router.get('/:id', this.getById)
this.router.put('/:id', this.updateUser)
@@ -63,13 +66,21 @@ class UserRouter {
app.use(this.router.allowedMethods())
}
async createUser (ctx, next) {
if (process.env.DISABLE_NEW_ACCOUNTS) {
await _this.validators.ensureAdmin(ctx, next)
}
await _this.userRESTController.createUser(ctx, next)
return true
}
async getAll (ctx, next) {
await _this.validators.ensureUser(ctx, next)
await _this.validators.ensureAdmin(ctx, next)
await _this.userRESTController.getUsers(ctx, next)
}
async getById (ctx, next) {
await _this.validators.ensureUser(ctx, next)
await _this.validators.ensureTargetUserOrAdmin(ctx, next)
await _this.userRESTController.getUser(ctx, next)
}
+5 -2
View File
@@ -1,6 +1,6 @@
/*
This Controller library is concerned with timer-based functions that are
kicked off periodicially.
kicked off periodically.
*/
import config from '../../config/index.js'
@@ -60,7 +60,7 @@ class TimerControllers {
clearInterval(this.gcOffersInt)
// clearInterval(this.checkDupOffers)
clearInterval(this.optimizeWalletHandle)
clearInterval(this.cleanusageHandle)
clearInterval(this.cleanUsageHandle)
}
// Garbage Collect the Orders.
@@ -114,6 +114,9 @@ class TimerControllers {
// Clean the usage state so that stats reflect the last 24 hours.
cleanUsage () {
try {
const now = new Date()
console.log(`cleanUsage() Timer Controller executing at ${now.toLocaleString()}`)
this.useCases.usage.cleanUsage()
return true
+13 -2
View File
@@ -537,7 +537,7 @@ class OfferUseCases {
orderData = await this.orderUseCase.findOrderByUtxo(offerData)
console.log(`orderData: ${JSON.stringify(orderData, null, 2)}`)
} catch (err) {
console.log('Order matching this Counter Offer is not managed by this instance of bch-dex. Skipping.')
console.log('Order matching this Counter Offer is not managed by this instance of bch-dex. Skipping.\n')
// Add order to list of seen orders, so that we don't spent time trying to validate it again.
this.seenOffers.push(eventId)
@@ -607,8 +607,19 @@ class OfferUseCases {
throw new Error(`The Counter Offer has an output address of ${addrInCounterOffer}, which does not match the Maker address of ${makerAddr} in the Offer.`)
}
// Get the User ID from the Order model.
const userId = orderData.userId
// Get the User model from the database.
this.UserModel = this.adapters.localdb.Users
const user = await this.UserModel.findById(userId)
console.log('user: ', user)
// Get the HD index from the Order model.
const hdIndex = orderData.hdIndex
// Sign and broadcast the transaction.
const txid = await this.adapters.wallet.completeTx(txHex, orderData.hdIndex)
const txid = await this.adapters.wallet.completeTx(txHex, hdIndex, user.mnemonic)
console.log('txid: ', txid)
return txid
+6 -2
View File
@@ -114,6 +114,7 @@ class OrderLib {
// Add P2WDB specific flag for signaling that this is a new offer.
orderEntity.dataType = 'offer'
orderEntity.userId = user._id
// Post the new Order information to Nostr under the topic set in the
// config file.
@@ -232,7 +233,7 @@ class OrderLib {
const order = await this.OrderModel.findOne({ utxoTxid: offerData.data.utxoTxid, utxoVout: offerData.data.utxoVout })
// const order = await this.OrderModel.findOne({ utxoTxid: offerData.data.utxoTxid })
// const order = await this.OrderModel.findOne({ tokenId: offerData.data.tokenId })
console.log('findOrderByUtxo() order: ', order)
console.log('\nfindOrderByUtxo() order: ', order)
if (!order) {
throw new Error('order not found')
@@ -246,7 +247,10 @@ class OrderLib {
return orderObject
} catch (err) {
console.error('Error in findOrderByUtxo(): ', err)
if (!err.message.toString().includes('order not found')) {
console.error('Error in findOrderByUtxo(): ', err)
}
throw err
}
}
+4
View File
@@ -36,7 +36,11 @@ class UsageUseCases {
const now = new Date()
const twentyFourHoursAgo = now.getTime() - (60000 * 60 * 24)
console.log('cleanUsage() now: ', now)
console.log('cleanUsage() restCalls.length before filtering: ', restCalls.length)
restCalls = restCalls.filter(x => x.timestamp > twentyFourHoursAgo)
console.log('cleanUsage() restCalls.length after filtering: ', restCalls.length)
return restCalls
} catch (err) {
console.error('Error in usage-use-cases.js/cleanUsage()')
-3
View File
@@ -1,3 +0,0 @@
/key/swarm/psk/1.0.0/
/base16/
bbd935b70105b03ebd0c6a3c2d2730cd22fc0d18c490ccf689b6c8a22e1bed2a
+133 -80
View File
@@ -5,16 +5,16 @@ import axios from 'axios'
import sinon from 'sinon'
import util from 'util'
import UserController from '../../../src/controllers/rest-api/users/controller.js'
import Adapters from '../../../src/adapters/index.js'
import UseCases from '../../../src/use-cases/index.js'
// import UserController from '../../../src/controllers/rest-api/users/controller.js'
// import Adapters from '../../../src/adapters/index.js'
// import UseCases from '../../../src/use-cases/index.js'
util.inspect.defaultOptions = { depth: 1 }
const LOCALHOST = `http://localhost:${config.port}`
const context = {}
const adapters = new Adapters()
let uut
// const adapters = new Adapters()
// let uut
let sandbox
// const mockContext = require('../../unit/mocks/ctx-mock').context
@@ -50,8 +50,8 @@ if (!config.noMongo) {
})
beforeEach(() => {
const useCases = new UseCases({ adapters })
uut = new UserController({ adapters, useCases })
// const useCases = new UseCases({ adapters })
// uut = new UserController({ adapters, useCases })
sandbox = sinon.createSandbox()
})
@@ -175,6 +175,59 @@ if (!config.noMongo) {
assert.equal(result.data.user.type, 'user')
assert.property(result.data.user, 'mnemonic')
})
it('should reject signup when DISABLE_NEW_ACCOUNTS is true', async () => {
try {
process.env.DISABLE_NEW_ACCOUNTS = true
const options = {
method: 'POST',
url: `${LOCALHOST}/users`,
data: {
email: 'test2@test.com',
password: 'supersecretpassword',
name: 'test3'
}
}
await axios(options)
assert(false, 'Unexpected result')
} catch (err) {
assert(err.response.status === 401, 'Error code 401 expected.')
}
})
it('admin can create a user when DISABLE_NEW_ACCOUNTS is true', async () => {
process.env.DISABLE_NEW_ACCOUNTS = true
const options = {
method: 'post',
url: `${LOCALHOST}/users`,
headers: {
Authorization: `Bearer ${context.adminJWT}`
},
data: {
user: {
email: 'fromAdmin@test.com',
password: 'supersecretpassword',
name: 'test3'
}
}
}
const result = await axios(options)
context.user = result.data.user
context.token = result.data.token
assert(result.status === 200, 'Status Code 200 expected.')
assert(
result.data.user.email === 'fromAdmin@test.com',
'Email of test expected'
)
assert(
result.data.user.password === undefined,
'Password expected to be omited'
)
assert.property(result.data, 'token', 'Token property exists.')
assert.equal(result.data.user.type, 'user')
})
})
describe('GET /users', () => {
@@ -250,52 +303,52 @@ if (!config.noMongo) {
}
})
it('should fetch all users', async () => {
const { token } = context
// it('should fetch all users', async () => {
// const { token } = context
const options = {
method: 'GET',
url: `${LOCALHOST}/users`,
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
}
}
const result = await axios(options)
// const options = {
// method: 'GET',
// url: `${LOCALHOST}/users`,
// headers: {
// Accept: 'application/json',
// Authorization: `Bearer ${token}`
// }
// }
// const result = await axios(options)
const users = result.data.users
// console.log(`users: ${util.inspect(users)}`)
// const users = result.data.users
// // console.log(`users: ${util.inspect(users)}`)
assert.hasAnyKeys(users[0], ['type', '_id', 'email', 'mnemonic'])
assert.isNumber(users.length)
})
// assert.hasAnyKeys(users[0], ['type', '_id', 'email', 'mnemonic'])
// assert.isNumber(users.length)
// })
it('should return a 422 http status if biz-logic throws an error', async () => {
try {
const { token } = context
// it('should return a 422 http status if biz-logic throws an error', async () => {
// try {
// const { token } = context
// Force an error
sandbox
.stub(uut.useCases.user, 'getAllUsers')
.rejects(new Error('test error'))
// // Force an error
// sandbox
// .stub(uut.useCases.user, 'getAllUsers')
// .rejects(new Error('test error'))
const options = {
method: 'GET',
url: `${LOCALHOST}/users`,
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
}
}
await axios(options)
// const options = {
// method: 'GET',
// url: `${LOCALHOST}/users`,
// headers: {
// Accept: 'application/json',
// Authorization: `Bearer ${token}`
// }
// }
// await axios(options)
assert.fail('Unexpected code path!')
} catch (err) {
// console.log(err)
assert.equal(err.response.status, 422)
assert.equal(err.response.data, 'test error')
}
})
// assert.fail('Unexpected code path!')
// } catch (err) {
// // console.log(err)
// assert.equal(err.response.status, 422)
// assert.equal(err.response.data, 'test error')
// }
// })
})
describe('GET /users/:id', () => {
@@ -317,45 +370,45 @@ if (!config.noMongo) {
}
})
it("should throw 404 if user doesn't exist", async () => {
const { token } = context
// it("should throw 404 if user doesn't exist", async () => {
// const { token } = context
try {
const options = {
method: 'GET',
url: `${LOCALHOST}/users/5fa4bd7ee1828f5f4d8ed004`,
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
}
}
await axios(options)
// try {
// const options = {
// method: 'GET',
// url: `${LOCALHOST}/users/5fa4bd7ee1828f5f4d8ed004`,
// headers: {
// Accept: 'application/json',
// Authorization: `Bearer ${token}`
// }
// }
// await axios(options)
assert.equal(true, false, 'Unexpected behavior')
} catch (err) {
assert.equal(err.response.status, 404)
}
})
// assert.equal(true, false, 'Unexpected behavior')
// } catch (err) {
// assert.equal(err.response.status, 404)
// }
// })
it('should throw 422 for invalid input', async () => {
const { token } = context
// it('should throw 422 for invalid input', async () => {
// const { token } = context
try {
const options = {
method: 'GET',
url: `${LOCALHOST}/users/1`,
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
}
}
await axios(options)
// try {
// const options = {
// method: 'GET',
// url: `${LOCALHOST}/users/1`,
// headers: {
// Accept: 'application/json',
// Authorization: `Bearer ${token}`
// }
// }
// await axios(options)
assert.equal(true, false, 'Unexpected behavior')
} catch (err) {
assert.equal(err.response.status, 422)
}
})
// assert.equal(true, false, 'Unexpected behavior')
// } catch (err) {
// assert.equal(err.response.status, 422)
// }
// })
it('should fetch own user', async () => {
const _id = context.user._id
+43 -28
View File
@@ -62,6 +62,7 @@ describe('Admin', () => {
describe('createSystemUser()', () => {
it('should create admin', async () => {
try {
await uut.deleteExistingSystemUser()
const result = await uut.createSystemUser()
assert.property(result, 'email')
@@ -72,44 +73,58 @@ describe('Admin', () => {
assert(false, 'Unexpected result')
}
})
it('should handle axios error', async () => {
it('should update admin password', async () => {
try {
const error1 = new Error('test error')
error1.response = {
status: 422
}
const error2 = new Error('test error')
error1.response = {
status: 500
}
// The loginAdmin() function in some use cases is recursive
// after handling the 422 error, it gets called again
sandbox
.stub(uut.axios, 'request')
.onFirstCall()
.throws(error1)
.onSecondCall()
.throws(error2)
uut.config.adminPassword = 'newpassword'
await uut.createSystemUser()
const fakeUser = {
password: 'oldpassword',
save: () => { return 'token' },
generateToken: () => { return 'token' }
}
sandbox.stub(uut.User, 'findOne').resolves(fakeUser)
const result = await uut.createSystemUser()
assert.property(result, 'email')
assert.property(result, 'password')
assert.property(result, 'id')
assert.property(result, 'token')
assert.equal(fakeUser.password, 'newpassword', 'password should be updated')
} catch (err) {
console.log(err)
assert(false, 'Unexpected result')
}
})
it('should handle error', async () => {
try {
sandbox.stub(uut.User, 'findOne').throws(new Error('test error'))
await uut.createSystemUser()
assert.fail('Unexpected result')
} catch (err) {
assert.include(err.message, 'test error')
}
})
})
it('should handle errors when remove user', async () => {
describe('deleteExistingSystemUser()', () => {
it('should delete admin', async () => {
try {
const error1 = new Error('test error')
error1.response = {
status: 422
}
sandbox.stub(uut.axios, 'request').throws(error1)
sandbox.stub(uut.User, 'deleteOne').throws(new Error('test error'))
await uut.createSystemUser()
sandbox.stub(uut.User, 'deleteOne').resolves(true)
const result = await uut.deleteExistingSystemUser()
assert.isTrue(result)
} catch (err) {
assert(false, 'Unexpected result')
}
})
it('should handle error when deleting admin', async () => {
try {
sandbox.stub(uut.User, 'deleteOne').throws(new Error('test error'))
await uut.deleteExistingSystemUser()
assert.fail('Unexpected result')
} catch (err) {
assert.include(err.message, 'test error')
}
+2 -1
View File
@@ -55,7 +55,8 @@ describe('#OrderPagination', () => {
rateInBaseUnit: 'rateInBaseUnit',
minUnitsToExchange: 'minUnitsToExchange',
ticker: 'ticker',
tokenType: 1
tokenType: 1,
userId: 'userId'
})
await order.save()
})
+21 -15
View File
@@ -43,6 +43,7 @@ describe('#wallet', () => {
})
const customWallet = new MockBchWallet()
customWallet.getKeyPair = () => { return { cashAddress: 'cashAddress', wif: 'wif', hdIndex: 11 } }
customWallet.sendTokens = () => { return 'move token tx id result' }
customWallet.utxos.utxoStore.slpUtxos.type1.tokens = [
{
@@ -100,22 +101,27 @@ describe('#wallet', () => {
})
})
describe('#completeTx', () => {
it('should complete a transaction', async () => {
sandbox.stub(uut, 'getKeyPair').resolves({
cashAddress: 'bitcoincash:qzl0d3gcqeypv4cy7gh8rgdszxa9vvm2acv7fqtd00',
wif: 'L5D2UAam8tvo3uii5kpgaGyjvVMimdrXu8nWGQSQjuuAix6ji1YQ',
hdIndex: 11
})
sandbox.stub(uut, 'deseralizeTx').resolves({
txid: 'complete tx id result'
})
sandbox.stub(uut.retryQueue, 'addToQueue').resolves('complete tx id result')
// TODO: This test needs to be refactored to use the new instanceWallet() method for loading the user wallet.
// it('should complete a transaction', async () => {
// sandbox.stub(uut, 'getKeyPair').resolves({
// cashAddress: 'bitcoincash:qzl0d3gcqeypv4cy7gh8rgdszxa9vvm2acv7fqtd00',
// wif: 'L5D2UAam8tvo3uii5kpgaGyjvVMimdrXu8nWGQSQjuuAix6ji1YQ',
// hdIndex: 11
// })
// sandbox.stub(uut, 'deseralizeTx').resolves({
// txid: 'complete tx id result'
// })
// sandbox.stub(uut.retryQueue, 'addToQueue').resolves('complete tx id result')
// const hex = 'hex'
// const hdIndex = 11
// const mnemonic = 'course abstract aerobic deer try switch turtle diet fence affair butter top'
// const txid = await uut.completeTx(hex, hdIndex, mnemonic)
// assert.equal(txid, 'complete tx id result')
// })
const hex = 'hex'
const hdIndex = 11
const txid = await uut.completeTx(hex, hdIndex)
assert.equal(txid, 'complete tx id result')
})
it('should throw an error if the hex is not provided', async () => {
try {
const hdIndex = 11
+6 -3
View File
@@ -1,6 +1,5 @@
/*
Unit tests for the use-cases/usage-use-cases.js business logic library.
Unit tests for the use-cases/usage-use-cases.js business logic library.
*/
// Public npm libraries
@@ -58,7 +57,7 @@ describe('#usage-use-case', () => {
// set older mock data
restCalls.push({
timestamp: now.getTime() - (60000 * 60 * 24),
timestamp: now.getTime() - (60000 * 60 * 48), // 48 hours ago
ip: '127.0.0.1'
})
@@ -88,6 +87,7 @@ describe('#usage-use-case', () => {
}
})
})
describe('#getRestSummary', () => {
it('should get the number of rest calls', () => {
// Set mock data
@@ -137,6 +137,7 @@ describe('#usage-use-case', () => {
assert.equal(result[0].ip, 'localhost')
assert.equal(result[0].cnt, '2')
})
it('should return a maximum of 20 values', () => {
// Fill Array with 21 values
for (let i = 0; i < 21; i++) {
@@ -154,6 +155,7 @@ describe('#usage-use-case', () => {
assert.equal(result.length, 20)
})
it('should handle error', () => {
try {
// Set mock data
@@ -194,6 +196,7 @@ describe('#usage-use-case', () => {
assert.equal(result[0].endpoint, 'GET /api/v1/users')
assert.equal(result[0].cnt, '2')
})
it('should return a maximum of 20 values', () => {
// Fill Array with 21 values
for (let i = 0; i < 21; i++) {
+3 -4
View File
@@ -1,8 +1,9 @@
import mongoose from 'mongoose'
import config from '../../config/index.js'
import User from '../../src/adapters/localdb/models/users.js'
const EMAIL = 'test@test.com'
const PASSWORD = 'pass'
const EMAIL = process.env.EMAIL || 'test@test3.com'
const PASSWORD = process.env.PASSWORD || 'pass'
async function addUser () {
// Connect to the Mongo Database.
@@ -13,8 +14,6 @@ async function addUser () {
{ useNewUrlParser: true, useUnifiedTopology: true }
)
const User = require('../../src/models/users')
const userData = {
email: EMAIL,
password: PASSWORD
+55
View File
@@ -0,0 +1,55 @@
/*
Use the system-user-dev.json file to log in as the admin user
and create a new user.
*/
// Global npm libraries
import axios from 'axios'
import fs from 'fs'
// Local libraries
// import config from '../../../config/index.js'
// import User from '../../../src/adapters/localdb/models/users.js'
// Customize these variables
const EMAIL = 'test@test.com'
const NAME = 'tester'
const PASSWORD = 'test'
async function createUser () {
try {
// Open the system-user-dev.json file
const systemUser = JSON.parse(fs.readFileSync('../../../config/system-user-dev.json', 'utf8'))
// Log in as the admin user
const adminLogin = {
email: systemUser.email,
password: systemUser.password
}
const response = await axios.post('http://localhost:5700/auth', adminLogin)
console.log(`response: ${JSON.stringify(response.data, null, 2)}`)
const jwt = response.data.token
// Create a new user, using the admin credentials
const options = {
method: 'post',
url: 'http://localhost:5700/users/',
headers: {
Authorization: `Bearer ${jwt}`
},
data: {
user: {
email: EMAIL,
name: NAME,
password: PASSWORD
}
}
}
const result = await axios(options)
console.log(`result: ${JSON.stringify(result.data, null, 2)}`)
} catch (err) {
console.error(err)
}
}
createUser()
@@ -1,6 +1,6 @@
import mongoose from 'mongoose'
import config from '../../config/index.js'
import User from '../../src/adapters/localdb/models/users.js'
import config from '../../../config/index.js'
import User from '../../../src/adapters/localdb/models/users.js'
async function getUsers () {
// Connect to the Mongo Database.
+57
View File
@@ -0,0 +1,57 @@
/*
Log in as an admin user to create a new user.
*/
// Global npm libraries
import axios from 'axios'
// import fs from 'fs'
// Local libraries
// import config from '../../../config/index.js'
// import User from '../../../src/adapters/localdb/models/users.js'
// Customize these variables
const EMAIL = 'someone@somewhere.com'
const NAME = 'Someone'
const PASSWORD = 'test'
const ADMIN_EMAIL = 'system@system.com'
const ADMIN_PASSWORD = 'admin'
async function createUser () {
try {
// Open the system-user-prod.json file
// const systemUser = JSON.parse(fs.readFileSync('../../../config/system-user-prod.json', 'utf8'))
// Log in as the admin user
const adminLogin = {
email: ADMIN_EMAIL,
password: ADMIN_PASSWORD
}
const response = await axios.post('http://localhost:5700/auth', adminLogin)
console.log(`response: ${JSON.stringify(response.data, null, 2)}`)
const jwt = response.data.token
// Create a new user, using the admin credentials
const options = {
method: 'post',
url: 'http://localhost:5700/users/',
headers: {
Authorization: `Bearer ${jwt}`
},
data: {
user: {
email: EMAIL,
name: NAME,
password: PASSWORD
}
}
}
const result = await axios(options)
console.log(`result: ${JSON.stringify(result.data, null, 2)}`)
} catch (err) {
console.error(err)
}
}
createUser()
+21
View File
@@ -0,0 +1,21 @@
import mongoose from 'mongoose'
// import config from '../../config/index.js'
import User from '../../../src/adapters/localdb/models/users.js'
const mongooseConnectStr = 'mongodb://172.17.0.1:5666/bch-swap-service-prod'
async function getUsers () {
// Connect to the Mongo Database.
mongoose.Promise = global.Promise
mongoose.set('useCreateIndex', true) // Stop deprecation warning.
await mongoose.connect(
mongooseConnectStr,
{ useNewUrlParser: true, useUnifiedTopology: true }
)
const users = await User.find({}, '-password')
console.log(`users: ${JSON.stringify(users, null, 2)}`)
mongoose.connection.close()
}
getUsers()
+83
View File
@@ -0,0 +1,83 @@
/*
This script will travers the HD wallet and sweep funds and tokens back
into the root address (index 0). That root address needs to have funds
to pay for the transactions.
This version will traverse the HD index of the wallet until it reaches
the value in the nextAddress property. This ensures that all UTXOs
that could be used by the wallet have been swept.
*/
// Public npm libraries
import BCHJS from '@psf/bch-js'
import BchTokenSweep from 'bch-token-sweep'
// Local libraries
import WalletAdapter from '../../src/adapters/wallet.js'
async function sweepFunds () {
try {
// Open the wallet files.
const wallet = new WalletAdapter()
const walletInfo = await wallet.openWallet()
const bchWallet = await wallet.instanceWallet(walletInfo)
console.log('walletInfo: ', walletInfo)
const lastIndex = walletInfo.nextAddress
const rootAddr = walletInfo.cashAddress
const rootWif = walletInfo.privateKey
console.log(`Sweeping all funds into root address ${rootAddr}...`)
// Generate an HD tree
const bchjs = new BCHJS()
const rootSeed = await bchjs.Mnemonic.toSeed(walletInfo.mnemonic)
const masterHDNode = bchjs.HDNode.fromSeed(rootSeed)
let hdIndex = 1
do {
// Generate a keypair from the HD wallet.
const childNode = masterHDNode.derivePath(`m/44'/245'/0'/0/${hdIndex}`)
const cashAddress = bchjs.HDNode.toCashAddress(childNode)
const wifToSweep = bchjs.HDNode.toWIF(childNode)
console.log(`\nSweeping HD Index ${hdIndex} with address ${cashAddress}`)
try {
// Sweep tokens from address
const sweeper = new BchTokenSweep(
wifToSweep,
rootWif,
bchWallet,
550,
rootAddr
)
await sweeper.populateObjectFromNetwork()
const hex = await sweeper.sweepTo(rootAddr)
// console.log(`hex: ${hex}`)
const txid = await sweeper.blockchain.broadcast(hex)
// console.log('Transaction ID', txid)
console.log(`Swept HD index ${hdIndex}. TXID: ${txid}`)
// Wait between loop iterations.
await bchjs.Util.sleep(3000)
} catch (err) {
console.log(`error message with index ${hdIndex}: ${err}`)
}
hdIndex++
} while (hdIndex <= lastIndex)
console.log(`${lastIndex} empty addresses detected. Exiting.`)
console.log('\n\nDo not forget to reset the nextAddress property in the wallet.json file!\n\n')
} catch (err) {
console.error('Error in sweepFunds(): ', err)
}
}
sweepFunds()