Bug fixes (client side)

Fixed Client page bugs:
- Fixed minor bugs in client side pages
- client page to use floGlobals.js
- moved KBucket.js to public (as its need by client page too).
Fixed Server Bugs:
- Added Access-Control-Allow-Origin to response headers
- Fixed: trustedIDs not loaded
- Fixed minor bugs (syntax errors)
This commit is contained in:
sairajzero 2022-01-25 01:28:22 +05:30
parent 8c1aad3d28
commit 2c35c545e8
7 changed files with 45 additions and 51 deletions

View File

@ -1,5 +1,6 @@
'use strict';
(function(){
/*Kademlia DHT K-bucket implementation as a binary tree.*/
/**
* Implementation of a Kademlia DHT k-bucket used for storing
@ -7,7 +8,7 @@
*
* @extends EventEmitter
*/
function BuildKBucket(options = {}) {
function BuildKBucket(options = {}) {
/**
* `options`:
* `distance`: Function
@ -401,7 +402,7 @@ function BuildKBucket(options = {}) {
}
}
module.exports = function K_Bucket(masterID, backupList) {
function K_Bucket(masterID, backupList) {
const decodeID = function(floID) {
let k = bitjs.Base58.decode(floID);
k.shift();
@ -457,4 +458,6 @@ module.exports = function K_Bucket(masterID, backupList) {
return (N == 1 ? nNodes[0] : nNodes);
};
}
};
('object' === typeof module) ? module.exports = K_Bucket : window.K_Bucket = K_Bucket;
})();

View File

@ -6,10 +6,9 @@ function exchangeAPI(api, options) {
let curPos = exchangeAPI.curPos || 0;
if (curPos >= nodeList.length)
return resolve('No Nodes online');
let url = nodeURL[nodeList[curPos]];
let url = "http://" + nodeURL[nodeList[curPos]];
(options ? fetch(url + api, options) : fetch(url + api))
.then(result => resolve(result)).catch(error => {
console.debug(error);
console.warn(nodeList[curPos], 'is offline');
//try next node
exchangeAPI.curPos = curPos + 1;
@ -102,7 +101,7 @@ function getAccount(floID, proxySecret) {
};
request.sign = signRequest({
type: "get_account",
timestamp: data.timestamp
timestamp: request.timestamp
}, proxySecret);
console.debug(request);
@ -168,7 +167,7 @@ function signRequest(request, privKey) {
function getLoginCode() {
return new Promise((resolve, reject) => {
exchangeAPI('/list-buyorders')
exchangeAPI('/get-login-code')
.then(result => responseParse(result)
.then(result => resolve(result))
.catch(error => reject(error)))
@ -249,7 +248,7 @@ function logout(floID, proxySecret) {
};
request.sign = signRequest({
type: "logout",
timestamp: data.timestamp
timestamp: request.timestamp
}, proxySecret);
console.debug(request);
@ -543,8 +542,8 @@ function refreshDataFromBlockchain() {
return new Promise((resolve, reject) => {
let nodes, lastTx;
try {
nodes = JSON.parse(localStorage.getItems('exhange-nodes'));
if (typeof nodes !== 'object')
nodes = JSON.parse(localStorage.getItem('exchange-nodes'));
if (typeof nodes !== 'object' || nodes === null)
throw Error('nodes must be an object')
else
lastTx = parseInt(localStorage.getItem('exchange-lastTx')) || 0;
@ -569,8 +568,8 @@ function refreshDataFromBlockchain() {
nodes[n] = content.Nodes.add[n];
}
});
localStorage.setItem('exhange-lastTx', result.totalTxs);
localStorage.setItem('exhange-nodes', JSON.stringify(nodes));
localStorage.setItem('exchange-lastTx', result.totalTxs);
localStorage.setItem('exchange-nodes', JSON.stringify(nodes));
nodeURL = nodes;
nodeKBucket = new K_Bucket(floGlobals.adminID, Object.keys(nodeURL));
nodeList = nodeKBucket.order;

View File

@ -12,27 +12,10 @@
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet">
<script id="floGlobals">
/* Constants for FLO blockchain operations !!Make sure to add this at beginning!! */
const floGlobals = {
//Required for all
blockchain: "FLO",
//Required for blockchain API operators
apiURL: {
FLO: ['https://livenet.flocha.in/', 'https://flosight.duckdns.org/'],
FLO_TEST: ['https://testnet-flosight.duckdns.org/', 'https://testnet.flocha.in/']
},
tokenURL: "https://ranchimallflo.duckdns.org/",
token: "rupee",
adminID: "FKAEdnPfjXLHSYwrXQu377ugN4tXU7VGdf",
sendAmt: 0.001,
fee: 0.0005,
}
</script>
<script src="floGlobals.js"></script>
<script src="https://sairajzero.github.io/Standard_Operations/cdn/floCrypto.js"></script>
<script src="https://github.com/sairajzero/Standard_Operations/releases/download/test/floBlockchainAPI.js"></script>
<script src="KBucket.js"></script>
<script src="fn.js"></script>
</head>
@ -1068,9 +1051,9 @@
showProcess('trade_button_wrapper')
try {
if (tradeType === 'buy') {
await buy(quantity, price, await proxy.secret)
await buy(quantity, price, proxy.userID, await proxy.secret)
} else {
await sell(quantity, price, await proxy.secret)
await sell(quantity, price, proxy.userID, await proxy.secret)
}
getRef('trade_button_wrapper').append(getRef('success_template').content.cloneNode(true))
notify(`Placed ${tradeType} order`, 'success')
@ -1218,9 +1201,9 @@
showWalletResult('success', `Sent ${asset} deposit request`, 'This may take upto 30 mins to reflect in your wallet.')
} else {
if (asset === 'FLO') {
await withdrawFLO(quantity, proxySecret)
await withdrawFLO(quantity, proxy.userID, proxySecret)
} else {
await withdrawRupee(quantity, proxySecret)
await withdrawRupee(quantity, proxy.userID, proxySecret)
}
showWalletResult('success', `Sent ${asset} withdraw request`, 'This may take upto 30 mins to reflect in your wallet.')
}
@ -1363,7 +1346,7 @@
const target = e.target.closest('.order-card')
const id = target.dataset.id
const type = target.dataset.type
cancelOrder(type, id, await proxy.secret)
cancelOrder(type, id, proxy.userID, await proxy.secret)
.then(() => {
notify('Order cancelled', 'success')
target.animate([
@ -1415,7 +1398,7 @@
if (res) {
try {
const proxy_secret = await proxy.secret;
const promises = [...selectedOrders].map(([id, type]) => cancelOrder(type, id, proxy_secret))
const promises = [...selectedOrders].map(([id, type]) => cancelOrder(type, id, proxy.userID, proxy_secret))
await Promise.all(promises)
selectedOrders.clear()
hideMyOrdersOptions()
@ -1687,7 +1670,7 @@
const balance = {}
let accountDetails = {}
function account() {
async function account() {
getAccount(proxy.userID, await proxy.secret).then(acc => {
getRef("login_form").classList.add('hide-completely')
getRef('home').classList.add('signed-in')
@ -1778,7 +1761,7 @@
refreshDataFromBlockchain().then(nodes => {
console.log(nodes);
refresh(true);
}).catch(error => reject(error))
}).catch(error => console.error(error))
})
</script>
</body>

View File

@ -37,6 +37,16 @@ module.exports = function App(secret, DB) {
}));
*/
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', "*");
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Pass to next layer of middleware
next();
})
//get code for login or signup
app.get('/get-login-code', Request.getLoginCode);
@ -47,7 +57,7 @@ module.exports = function App(secret, DB) {
app.post('/login', Request.Login);
//logout request
app.get('/logout', Request.Logout);
app.post('/logout', Request.Logout);
//place sell or buy order
app.post('/buy', Request.PlaceBuyOrder);
@ -65,7 +75,7 @@ module.exports = function App(secret, DB) {
app.get('/get-rate', Request.getRate)
//get account details
app.get('/account', Request.Account);
app.post('/account', Request.Account);
//withdraw and deposit request
app.post('/deposit-flo', Request.DepositFLO);

View File

@ -1,6 +1,6 @@
'use strict';
const K_Bucket = require('./KBucket');
const K_Bucket = require('../../public/KBucket');
const slave = require('./slave');
const WebSocket = require('ws');
const shareThreshold = 50 / 100;

View File

@ -27,7 +27,6 @@ function refreshDataFromBlockchain() {
return new Promise((resolve, reject) => {
DB.query("SELECT num FROM lastTx WHERE floID=?", [floGlobals.adminID]).then(result => {
let lastTx = result.length ? result[0].num : 0;
console.debug('lastTx', lastTx);
floBlockchainAPI.readData(floGlobals.adminID, {
ignoreOld: lastTx,
sentOnly: true,
@ -38,7 +37,6 @@ function refreshDataFromBlockchain() {
trusted_change = false;
result.data.reverse().forEach(data => {
var content = JSON.parse(data)[floGlobals.application];
console.debug(content);
//Node List
if (content.Nodes) {
nodes_change = true;
@ -95,7 +93,7 @@ function loadDataFromDB(changes, startup) {
if (startup || changes.nodes)
promises.push(loadDataFromDB.nodeList());
if (startup || changes.trusted)
promises.push(loadDataFromDB.trustedIDs);
promises.push(loadDataFromDB.trustedIDs());
Promise.all(promises)
.then(_ => resolve("Data load successful"))
.catch(error => reject(error))

View File

@ -29,12 +29,12 @@ function validateRequestFromFloID(request, sign, floID, proxy = true) {
if (!serving)
return reject(INVALID(INVALID_SERVER_MSG));
else if (!floCrypto.validateAddr(floID))
return res.status(INVALID.e_code).send("Invalid floID");
return reject(INVALID.e_code).send("Invalid floID");
DB.query("SELECT " + (proxy ? "session_time, proxyKey AS pubKey FROM Sessions" : "pubKey FROM Users") + " WHERE floID=?", [floID]).then(result => {
if (result.length < 1)
return reject(INVALID(proxy ? "Session not active" : "User not registered"));
if (proxy && result[0].session_time + maxSessionTimeout < Date.now())
return res.status(INVALID.e_code).send("Session Expired! Re-login required");
return reject(INVALID.e_code).send("Session Expired! Re-login required");
let req_str = validateRequest(request, sign, result[0].pubKey);
req_str instanceof INVALID ? reject(req_str) : resolve(req_str);
}).catch(error => reject(error));
@ -64,7 +64,7 @@ function storeRequest(floID, req_str, sign) {
function getLoginCode(req, res) {
let randID = floCrypto.randString(8, true) + Math.round(Date.now() / 1000);
let hash = Crypto.SHA1(randID + secret);
res.status(INVALID.e_code).send({
res.send({
code: randID,
hash: hash
});
@ -111,9 +111,9 @@ function Login(req, res) {
proxyKey: data.proxyKey,
timestamp: data.timestamp
}, data.sign, data.floID, false).then(req_str => {
DB.query("INSERT INTO Sessions (floID, proxyKey) VALUES (?, ?, ?) " +
"ON DUPLICATE KEY UPDATE session_time=DEFAULT, proxyKey=?",
[data.floID, data.code, data.proxyKey, data.code, data.proxyKey]).then(_ => {
DB.query("INSERT INTO Sessions (floID, proxyKey) VALUE (?, ?) AS new " +
"ON DUPLICATE KEY UPDATE session_time=DEFAULT, proxyKey=new.proxyKey",
[data.floID, data.proxyKey]).then(_ => {
storeRequest(data.floID, req_str, data.sign);
res.send("Login Successful");
}).catch(error => {
@ -131,6 +131,7 @@ function Login(req, res) {
}
function Logout(req, res) {
let data = req.body;
validateRequestFromFloID({
type: "logout",
timestamp: data.timestamp