fixed get sharable data function

This commit is contained in:
Abhishek Sinha 2019-01-04 15:47:31 +05:30
parent ea5ec88785
commit 9959e1cdba

View File

@ -5,7 +5,7 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>LocalBitcoinPlusPlus</title> <title>Document</title>
<style> <style>
.tradebox { .tradebox {
@ -9145,34 +9145,12 @@
doSend(sync_request); doSend(sync_request);
}, },
get_sharable_db_data: function(callback) { get_sharable_db_data: async function(dbTableNamesArray) {
let sharable_data = {}; let arr = {};
for (const elem of dbTableNamesArray) {
readAllDB("buyOrders", function(buyOrdersres) { await readAllDB(elem).then(e=>arr[elem]=e);
sharable_data.buyOrders = buyOrdersres; }
return arr;
readAllDB("sellOrders", function(sellOrdersres) {
sharable_data.sellOrders = sellOrdersres;
readAllDB("btc_balances", function(btc_balancesres) {
sharable_data.btc_balances = btc_balancesres;
readAllDB("cash_balances", function(cash_balancesres) {
sharable_data.cash_balances = cash_balancesres;
readAllDB("deposit", function(depositres) {
sharable_data.deposit = depositres;
readAllDB("withdraw_cash", function(withdraw_cashres) {
sharable_data.withdraw_cash = withdraw_cashres;
return callback(sharable_data);
});
});
});
});
});
});
}, },
claim_deposit_withdraw: function(claim_id) { claim_deposit_withdraw: function(claim_id) {
@ -9251,9 +9229,8 @@
<!-- Wallet Operations (Generate, Sign and Verify) --> <!-- Wallet Operations (Generate, Sign and Verify) -->
<script> <script>
var wallets = localbitcoinplusplus.wallets = function (wallets) { var wallets = localbitcoinplusplus.wallets = function (wallets) {};
};
const MY_PRIVATE_KEY_SHAMIRS_SHARES = localbitcoinplusplus.wallets.private_key_shamirs_secrets_shares = []; const MY_PRIVATE_KEY_SHAMIRS_SHARES = localbitcoinplusplus.wallets.private_key_shamirs_secrets_shares = [];
wallets.prototype = { wallets.prototype = {
@ -9356,8 +9333,8 @@
return my_pvt_key; return my_pvt_key;
}, },
getUserPublicKey: function(flo_address, callback) { getUserPublicKey: function(flo_address, callback) {
readDB('userPublicData', flo_address, function(res) { readDB('userPublicData', flo_address).then(function(res) {
if (typeof res=="object") { if (typeof res=="object" && typeof res.trader_flo_pubKey=="string") {
return callback(res.trader_flo_pubKey); return callback(res.trader_flo_pubKey);
} }
}); });
@ -9399,51 +9376,50 @@
var request = JSON.parse(request); var request = JSON.parse(request);
var params = request.params[0]; var params = request.params[0];
var method = request.method; var method = request.method;
if (typeof params == "object" && typeof method == "string") { if (typeof params == "object" && typeof method == "string") {
// if (typeof params.trader_flo_address != "string" && params.trader_flo_address.length < 1) {
// throw new Error("Unknown trader id.");
// }
let respective_trader_id = ''; let respective_trader_id = '';
if (typeof params.trader_flo_address != "string") respective_trader_id = params.trader_flo_address; if (typeof params.trader_flo_address == "string") respective_trader_id = params.trader_flo_address;
request.response = {}; request.response = {};
/** CHECK HERE IF USER IS INDULGED IN ANY MORE TRADE. /** CHECK HERE IF USER IS INDULGED IN ANY MORE TRADE.
IF TRUE RETURN ERROR */ IF TRUE RETURN ERROR */
// readAllDB("deposit", function(res) { // readAllDB("deposit").then(function(res) {
// if (typeof res == "object" && res.length>0) { // if (typeof res == "object" && res.length>0) {
// let canUserTrade = res.map(function(user) { // let canUserTrade = res.map(function(user) {
// return respective_trader_id == user.trader_flo_address; // return respective_trader_id == user.trader_flo_address;
// }); // });
// if (canUserTrade.includes(true)) { // if (canUserTrade.includes(true)) {
// request.response = `Trader id ${respective_trader_id} is not clear for trade currently. // request.response = `Trader id ${respective_trader_id} is not clear for trade currently.
// You must finish your previous pending orders to qualify again to trade.`; // You must finish your previous pending orders to qualify again to trade.`;
// return false; // return false;
// } // }
// } // }
// }); // });
// Check if user id is in deposit or withdraw. If true prevent him from trading // Check if user id is in deposit or withdraw. If true prevent him from trading
try { // try {
readAllDB('withdraw_cash', function(res) { // readAllDB('withdraw_cash').then(function(res) {
let check_deposit_withdraw_id_array = res.filter(f=>f.status===2) // if (typeof res=="object") {
.map(m=>{ // let check_deposit_withdraw_id_array = res.filter(f=>f.status===2)
if (m.trader_flo_address==respective_trader_id||m.deposit_withdraw_id_array==respective_trader_id) { // .map(m=>{
let server_msg = `Trader id ${respective_trader_id} is not clear for trade currently. // if (m.trader_flo_address==respective_trader_id||m.deposit_withdraw_id_array==respective_trader_id) {
You must finish your previous pending deposit/withdraw action to qualify again to trade.`; // let server_msg = `Trader id ${respective_trader_id} is not clear for trade currently.
// You must finish your previous pending deposit/withdraw action to qualify again to trade.`;
let server_response = localbitcoinplusplus.rpc.prototype // let server_response = localbitcoinplusplus.rpc.prototype
.send_rpc // .send_rpc
.call(this, "supernode_message", // .call(this, "supernode_message",
{"trader_flo_id":respective_trader_id, "server_msg":server_msg}); // {"trader_flo_id":respective_trader_id, "server_msg":server_msg});
doSend(server_response); // doSend(server_response);
throw new Error("User has not finished previous pending actions."); // throw new Error("User has not finished previous pending actions.");
} // }
}); // });
}); // }
} catch (error) { // });
throw new Error(error); // } catch (error) {
} // throw new Error(error);
// }
switch (method) { switch (method) {
case "trade_buy": case "trade_buy":
@ -9494,7 +9470,8 @@
case "sync_with_supernode": case "sync_with_supernode":
localbitcoinplusplus.rpc.prototype.filter_legit_requests(function (is_valid_request) { localbitcoinplusplus.rpc.prototype.filter_legit_requests(function (is_valid_request) {
if (is_valid_request === true && params.job=="SYNC_MY_LOCAL_DB_WITH_SUPERNODE_DB" && params.trader_flo_address.length>0) { if (is_valid_request === true && params.job=="SYNC_MY_LOCAL_DB_WITH_SUPERNODE_DB" && params.trader_flo_address.length>0) {
localbitcoinplusplus.actions.get_sharable_db_data(function(su_db_data) { const tableArray = ["deposit", "withdraw_cash", "withdraw_btc", "btc_balances", "cash_balances", "userPublicData", "supernode_private_key_chunks"];
localbitcoinplusplus.actions.get_sharable_db_data(tableArray).then(function(su_db_data) {
if (typeof su_db_data == "object") { if (typeof su_db_data == "object") {
su_db_data.trader_flo_address = params.trader_flo_address; su_db_data.trader_flo_address = params.trader_flo_address;
let server_sync_response = localbitcoinplusplus.rpc.prototype let server_sync_response = localbitcoinplusplus.rpc.prototype
@ -9507,7 +9484,6 @@
}); });
} }
}); });
break; break;
case "deposit_asset_request": case "deposit_asset_request":
localbitcoinplusplus.rpc.prototype.filter_legit_requests(function (is_valid_request) { localbitcoinplusplus.rpc.prototype.filter_legit_requests(function (is_valid_request) {
@ -9559,12 +9535,13 @@
throw new Error('Failed to determine Super node signing key.'); throw new Error('Failed to determine Super node signing key.');
} }
readDB("localbitcoinUser", "00-01", function (su_data) { readDB("localbitcoinUser", "00-01").then(function (su_data) {
if (typeof su_data == "object" && typeof su_data.myLocalFLOPublicKey == if (typeof su_data == "object" && typeof su_data.myLocalFLOPublicKey ==
"string" && "string" &&
su_data.myLocalFLOPublicKey.length > 0 && su_data.myLocalFLOPublicKey.length > 0 &&
localbitcoinplusplus.master_configurations.supernodesPubKeys localbitcoinplusplus.master_configurations.supernodesPubKeys
.includes(su_data.myLocalFLOPublicKey)) { .includes(su_data.myLocalFLOPublicKey)) {
let receivedTradeInfoHash = Crypto.SHA256(JSON.stringify( let receivedTradeInfoHash = Crypto.SHA256(JSON.stringify(
receivedTradeInfo)); receivedTradeInfo));
@ -9669,7 +9646,7 @@
params.status = 1; params.status = 1;
let receivedTradeInfo = { ...params }; let receivedTradeInfo = { ...params };
readDB("localbitcoinUser", "00-01", function (su_data) { readDB("localbitcoinUser", "00-01").then(function (su_data) {
if (typeof su_data == "object" && typeof su_data.myLocalFLOPublicKey == if (typeof su_data == "object" && typeof su_data.myLocalFLOPublicKey ==
"string" && "string" &&
su_data.myLocalFLOPublicKey.length > 0 && su_data.myLocalFLOPublicKey.length > 0 &&
@ -9690,7 +9667,7 @@
// YOU NEED TO DETERMINE A BANK ACCOUNT HERE IF NO ONE IS WITHDRAWING // YOU NEED TO DETERMINE A BANK ACCOUNT HERE IF NO ONE IS WITHDRAWING
try { try {
addDB("deposit", receivedTradeInfo); addDB("deposit", receivedTradeInfo);
readDBbyIndex("withdraw_cash", "status", 1, readDBbyIndex("withdraw_cash", "status", 1).then(
function ( function (
withdrawers_list) { withdrawers_list) {
if (typeof withdrawers_list == if (typeof withdrawers_list ==
@ -9811,7 +9788,7 @@
params.status = 1; params.status = 1;
if (params.product == "BTC") { if (params.product == "BTC") {
// Check how much Bitcoins the user can withdraw // Check how much Bitcoins the user can withdraw
readDB("btc_balances", params.trader_flo_address, function ( readDB("btc_balances", params.trader_flo_address).then(function (
btc_balance_res) { btc_balance_res) {
if (typeof btc_balance_res == "object" && typeof btc_balance_res if (typeof btc_balance_res == "object" && typeof btc_balance_res
.trader_flo_address == "string" && .trader_flo_address == "string" &&
@ -9838,7 +9815,7 @@
let receiverBTCAddress = params.receivinAddress let receiverBTCAddress = params.receivinAddress
.trim(); .trim();
readAllDB("deposit", function (deposit_list) { readAllDB("deposit").then(function (deposit_list) {
if (typeof deposit_list == "object" && if (typeof deposit_list == "object" &&
deposit_list.length > 0) { deposit_list.length > 0) {
deposit_list = deposit_list.filter( deposit_list = deposit_list.filter(
@ -9878,7 +9855,7 @@
// doSend btc_private_key_shamirs_id from system_btc_reserves_private_keys // doSend btc_private_key_shamirs_id from system_btc_reserves_private_keys
valid_btc_list.map(vbl=>{ valid_btc_list.map(vbl=>{
readDBbyIndex('system_btc_reserves_private_keys', 'btc_address', vbl.deposited_btc_address, function(res) { readDBbyIndex('system_btc_reserves_private_keys', 'btc_address', vbl.deposited_btc_address).then(function(res) {
let retrieve_pvtkey_req_id = res[0].id; let retrieve_pvtkey_req_id = res[0].id;
res[0].btc_private_key_shamirs_id.map(bpks=>{ res[0].btc_private_key_shamirs_id.map(bpks=>{
let retrieve_pvtkey_req = localbitcoinplusplus.rpc.prototype let retrieve_pvtkey_req = localbitcoinplusplus.rpc.prototype
@ -9920,7 +9897,7 @@
AND RECEIVER HAS CONFIRMED WITHDRAW*/ AND RECEIVER HAS CONFIRMED WITHDRAW*/
// Check how much Cash user can withdraw // Check how much Cash user can withdraw
readDB("cash_balances", params.trader_flo_address, function ( readDB("cash_balances", params.trader_flo_address).then(function (
cash_balances_res) { cash_balances_res) {
if (typeof cash_balances_res == "object" && typeof cash_balances_res if (typeof cash_balances_res == "object" && typeof cash_balances_res
.trader_flo_address == "string" && .trader_flo_address == "string" &&
@ -9943,7 +9920,7 @@
status: 1 // withdraw request called status: 1 // withdraw request called
} }
readDB("localbitcoinUser", "00-01", function ( readDB("localbitcoinUser", "00-01").then(function (
su_data) { su_data) {
if (typeof su_data == "object" && if (typeof su_data == "object" &&
typeof su_data.myLocalFLOPublicKey == typeof su_data.myLocalFLOPublicKey ==
@ -10034,9 +10011,9 @@
if(typeof pkChunks.private_key_chunk !== "undefined") return pkChunks.private_key_chunk.privateKeyChunks; if(typeof pkChunks.private_key_chunk !== "undefined") return pkChunks.private_key_chunk.privateKeyChunks;
}).filter(val => val !== undefined); }).filter(val => val !== undefined);
readDB('withdraw_btc', withdraw_id, function(withdraw_res) { readDB('withdraw_btc', withdraw_id).then(function(withdraw_res) {
if (typeof withdraw_res == "object") { if (typeof withdraw_res == "object") {
readDB('system_btc_reserves_private_keys', retrieve_pvtkey_req_id, function(btc_reserves) { readDB('system_btc_reserves_private_keys', retrieve_pvtkey_req_id).then(function(btc_reserves) {
if (typeof btc_reserves == "object") { if (typeof btc_reserves == "object") {
let transaction_key = btc_reserves.supernode_transaction_key; let transaction_key = btc_reserves.supernode_transaction_key;
if (transaction_key.length>0) { if (transaction_key.length>0) {
@ -10062,7 +10039,7 @@
readDBbyIndex('deposit', 'btc_address', withdraw_res.utxo_addr, function(deposit_arr) { readDBbyIndex('deposit', 'btc_address', withdraw_res.utxo_addr).then(function(deposit_arr) {
if (typeof deposit_arr=="object") { if (typeof deposit_arr=="object") {
let eqBTC = localbitcoinplusplus.trade.prototype.calculateBTCEquivalentOfCash(withdraw_res.receiverBTCEquivalentInCash); let eqBTC = localbitcoinplusplus.trade.prototype.calculateBTCEquivalentOfCash(withdraw_res.receiverBTCEquivalentInCash);
eqBTC = parseFloat(eqBTC); eqBTC = parseFloat(eqBTC);
@ -10255,7 +10232,7 @@
} }
//Check buyer's INR balance //Check buyer's INR balance
readDB("cash_balances", params.trader_flo_address, function (res) { readDB("cash_balances", params.trader_flo_address).then(function (res) {
if (typeof res !== "undefined" && typeof res.cash_balance == "number" && !isNaN(res.cash_balance)) { if (typeof res !== "undefined" && typeof res.cash_balance == "number" && !isNaN(res.cash_balance)) {
let buyer_cash_balance = parseFloat(res.cash_balance); let buyer_cash_balance = parseFloat(res.cash_balance);
let buy_price_btc = parseFloat(params.buy_price); let buy_price_btc = parseFloat(params.buy_price);
@ -10271,7 +10248,7 @@
let res_btc; let res_btc;
// supernode data query // supernode data query
readDB('localbitcoinUser', '00-01', function (user_data) { readDB('localbitcoinUser', '00-01').then(function (user_data) {
if (typeof user_data == "object" && typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY == if (typeof user_data == "object" && typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY ==
"string" && localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY.length > "string" && localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY.length >
0) { 0) {
@ -10320,7 +10297,7 @@
} }
// Check BTC balance of the seller // Check BTC balance of the seller
readDB("btc_balances", params.trader_flo_address, function (res) { readDB("btc_balances", params.trader_flo_address).then(function (res) {
if (typeof res !== "undefined" && typeof res.trader_flo_address == "string" && res.trader_flo_address if (typeof res !== "undefined" && typeof res.trader_flo_address == "string" && res.trader_flo_address
.length > 0 && .length > 0 &&
typeof res.btc_balance == "number" && res.btc_balance > 0) { typeof res.btc_balance == "number" && res.btc_balance > 0) {
@ -10336,7 +10313,7 @@
} }
// supernode data query // supernode data query
readDB('localbitcoinUser', '00-01', function (user_data) { readDB('localbitcoinUser', '00-01').then(function (user_data) {
if (typeof user_data == "object" && typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY == if (typeof user_data == "object" && typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY ==
"string" && localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY.length > 0) { "string" && localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY.length > 0) {
@ -10376,8 +10353,6 @@
throw new Error("Invalid amount error."); throw new Error("Invalid amount error.");
} else if (userFLOaddress.length < 0) { } else if (userFLOaddress.length < 0) {
throw new Error("User address required."); throw new Error("User address required.");
} else if (userFloPublicKey.length < 0) {
throw new Error("User address required.");
} }
let deposit_request_object = { let deposit_request_object = {
@ -10526,9 +10501,9 @@
/*Finds the best buy sell id match for a trade*/ /*Finds the best buy sell id match for a trade*/
createTradePipes() { createTradePipes() {
try { try {
readAllDB("sellOrders", function (sellOrdersList) { readAllDB("sellOrders").then(function (sellOrdersList) {
if (sellOrdersList.length > 0) { if (sellOrdersList.length > 0) {
readAllDB("buyOrders", function (buyOrdersList) { readAllDB("buyOrders").then(function (buyOrdersList) {
if (buyOrdersList.length > 0) { if (buyOrdersList.length > 0) {
localbitcoinplusplus.master_configurations.validTradingAmount.map( localbitcoinplusplus.master_configurations.validTradingAmount.map(
li => { li => {
@ -10585,7 +10560,7 @@
buyPipeObj.buy_price == sellPipeObj.buy_price buyPipeObj.buy_price == sellPipeObj.buy_price
) { ) {
// Check buyer's cash balance // Check buyer's cash balance
readDB("cash_balances", buyPipeObj.trader_flo_address, function (buyPipeCashRes) { readDB("cash_balances", buyPipeObj.trader_flo_address).then(function (buyPipeCashRes) {
if (typeof buyPipeCashRes == "object" && typeof buyPipeCashRes.cash_balance == if (typeof buyPipeCashRes == "object" && typeof buyPipeCashRes.cash_balance ==
"number") { "number") {
let buyer_cash_balance = parseFloat(buyPipeCashRes.cash_balance); let buyer_cash_balance = parseFloat(buyPipeCashRes.cash_balance);
@ -10602,7 +10577,7 @@
} }
// Check seller's BTC balance // Check seller's BTC balance
readDB("btc_balances", sellPipeObj.trader_flo_address, function (sellPipeBTCRes) { readDB("btc_balances", sellPipeObj.trader_flo_address).then(function (sellPipeBTCRes) {
if (typeof sellPipeBTCRes == "object" && typeof sellPipeBTCRes.btc_balance == if (typeof sellPipeBTCRes == "object" && typeof sellPipeBTCRes.btc_balance ==
"number") { "number") {
let seller_btc_balance = parseFloat(sellPipeBTCRes.btc_balance) let seller_btc_balance = parseFloat(sellPipeBTCRes.btc_balance)
@ -10619,7 +10594,7 @@
// Increase buyer's BTC balance // Increase buyer's BTC balance
let buyerBTCResponseObject; let buyerBTCResponseObject;
readDB("btc_balances", buyPipeObj.trader_flo_address, readDB("btc_balances", buyPipeObj.trader_flo_address).then(
function (buyPipeBTCRes) { function (buyPipeBTCRes) {
if (typeof buyPipeBTCRes == "object" && typeof buyPipeBTCRes if (typeof buyPipeBTCRes == "object" && typeof buyPipeBTCRes
.btc_balance == "number") { .btc_balance == "number") {
@ -10646,7 +10621,7 @@
// Increase seller's Cash balance // Increase seller's Cash balance
let sellerCashResponseObject; let sellerCashResponseObject;
readDB("cash_balances", sellPipeObj.trader_flo_address, readDB("cash_balances", sellPipeObj.trader_flo_address).then(
function (sellPipeCashRes) { function (sellPipeCashRes) {
if (typeof sellPipeCashRes == if (typeof sellPipeCashRes ==
"object" && typeof sellPipeCashRes "object" && typeof sellPipeCashRes
@ -10678,7 +10653,7 @@
} }
// supernode data query // supernode data query
readDB('localbitcoinUser', '00-01', readDB('localbitcoinUser', '00-01').then(
function (user_data) { function (user_data) {
if (typeof user_data == if (typeof user_data ==
"object" && typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY == "object" && typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY ==
@ -11086,15 +11061,17 @@
var res = response.substr(res_pos); var res = response.substr(res_pos);
try { try {
var res_obj = JSON.parse(res); var res_obj = JSON.parse(res);
if (typeof res_obj.method !== undefined) { if (typeof res_obj.method !== undefined) {
let response_from_sever; let response_from_sever;
switch (res_obj.method) { switch (res_obj.method) {
case "supernode_message": case "supernode_message":
if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object") { if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object") {
let received_resp = res_obj.params[0]; let received_resp = res_obj.params[0];
try { try {
if (received_resp.trader_flo_id.length>0 && received_resp.server_msg.length>0) { if (received_resp.trader_flo_id.length>0 && received_resp.server_msg.length>0) {
readDB("localbitcoinUser", "00-01", function(res) { readDB("localbitcoinUser", "00-01").then(function(res) {
if (typeof res=="object" && res.myLocalFLOAddress.length>0) { if (typeof res=="object" && res.myLocalFLOAddress.length>0) {
if (res.myLocalFLOAddress===received_resp.trader_flo_id) { if (res.myLocalFLOAddress===received_resp.trader_flo_id) {
writeToScreen(received_resp.server_msg); writeToScreen(received_resp.server_msg);
@ -11166,7 +11143,7 @@
if (tableStoreName=='trader_flo_address' || !su_db_data.hasOwnProperty(tableStoreName)) continue; if (tableStoreName=='trader_flo_address' || !su_db_data.hasOwnProperty(tableStoreName)) continue;
try { try {
removeAllinDB(tableStoreName, function(res) { removeAllinDB(tableStoreName).then(function(res) {
if (res!==false) { if (res!==false) {
var obj = su_db_data[res]; var obj = su_db_data[res];
if (obj.length>0) { if (obj.length>0) {
@ -11205,7 +11182,7 @@
if (typeof resp.withdrawer_data=="object") { if (typeof resp.withdrawer_data=="object") {
updateinDB("withdraw_cash", resp.withdrawer_data, resp.withdrawer_data.trader_flo_address); updateinDB("withdraw_cash", resp.withdrawer_data, resp.withdrawer_data.trader_flo_address);
} }
readDB("localbitcoinUser", "00-01", function (user) { readDB("localbitcoinUser", "00-01").then(function (user) {
if (typeof user == "object" && user.myLocalFLOAddress == resp.data.trader_flo_address) { if (typeof user == "object" && user.myLocalFLOAddress == resp.data.trader_flo_address) {
let counterTraderAccountAddress = let counterTraderAccountAddress =
`<p><strong>Please pay the amount to following address:</strong></p> `<p><strong>Please pay the amount to following address:</strong></p>
@ -11283,7 +11260,7 @@
break; break;
case "send_back_shamirs_secret_supernode_pvtkey": case "send_back_shamirs_secret_supernode_pvtkey":
if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object") { if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object") {
readDB("supernode_private_key_chunks", res_obj.params[0].chunk_val, function(res) { readDB("supernode_private_key_chunks", res_obj.params[0].chunk_val).then(function(res) {
let send_pvtkey_req = localbitcoinplusplus.rpc.prototype let send_pvtkey_req = localbitcoinplusplus.rpc.prototype
.send_rpc .send_rpc
.call(this, "retrieve_shamirs_secret_supernode_pvtkey", .call(this, "retrieve_shamirs_secret_supernode_pvtkey",
@ -11293,6 +11270,7 @@
} }
break; break;
case "retrieve_shamirs_secret_supernode_pvtkey": case "retrieve_shamirs_secret_supernode_pvtkey":
if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object" if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object"
&& typeof res_obj.params[0].private_key_chunk=="object" && typeof res_obj.params[0].private_key_chunk=="object"
&& typeof localbitcoinplusplus.wallets.supernode_transaction_key == "object") { && typeof localbitcoinplusplus.wallets.supernode_transaction_key == "object") {
@ -11307,9 +11285,7 @@
break; break;
case "send_back_shamirs_secret_btc_pvtkey": case "send_back_shamirs_secret_btc_pvtkey":
if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object") { if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object") {
readDB("supernode_private_key_chunks", res_obj.params[0].chunk_val, function(res) { readDB("supernode_private_key_chunks", res_obj.params[0].chunk_val).then(function(res) {
console.log(res);
let send_pvtkey_req = localbitcoinplusplus.rpc.prototype let send_pvtkey_req = localbitcoinplusplus.rpc.prototype
.send_rpc .send_rpc
.call(this, "retrieve_shamirs_secret_btc_pvtkey", .call(this, "retrieve_shamirs_secret_btc_pvtkey",
@ -11363,7 +11339,7 @@
user_claim_request.sign, user_claim_request.userPubKey)) { user_claim_request.sign, user_claim_request.userPubKey)) {
//If the request is valid, find out if the requester is depositor or withdrawer //If the request is valid, find out if the requester is depositor or withdrawer
readDB("withdraw_cash", withdraw_order_id, function(withdraw_data) { readDB("withdraw_cash", withdraw_order_id).then(function(withdraw_data) {
if (typeof withdraw_data=="object") { if (typeof withdraw_data=="object") {
if (withdraw_data.depositor_flo_id==user_id) { if (withdraw_data.depositor_flo_id==user_id) {
// Depositor claimed to deposit the cash // Depositor claimed to deposit the cash
@ -11386,7 +11362,7 @@
doSend(update_withdraw_cash_obj); doSend(update_withdraw_cash_obj);
} else if (withdraw_data.trader_flo_address==user_id) { } else if (withdraw_data.trader_flo_address==user_id) {
// Withdrawer confirmed the payment // Withdrawer confirmed the payment
readDBbyIndex('cash_balances', 'trader_flo_address', withdraw_data.depositor_flo_id, function(depositor_cash_data) { readDBbyIndex('cash_balances', 'trader_flo_address', withdraw_data.depositor_flo_id).then(function(depositor_cash_data) {
if (typeof depositor_cash_data=="object") { if (typeof depositor_cash_data=="object") {
if (depositor_cash_data.length==0) { if (depositor_cash_data.length==0) {
depositor_cash_data = {cash_balance:0, trader_flo_address:withdraw_data.depositor_flo_id}; depositor_cash_data = {cash_balance:0, trader_flo_address:withdraw_data.depositor_flo_id};
@ -11394,7 +11370,7 @@
} }
depositor_cash_data.cash_balance += parseFloat(withdraw_data.withdraw_amount); depositor_cash_data.cash_balance += parseFloat(withdraw_data.withdraw_amount);
updateinDB('cash_balances', depositor_cash_data); updateinDB('cash_balances', depositor_cash_data);
removeByIndex('deposit', 'trader_flo_address', depositor_cash_data.trader_flo_address, function() {}); removeByIndex('deposit', 'trader_flo_address', depositor_cash_data.trader_flo_address);
removeinDB('withdraw_cash', withdraw_data.id); removeinDB('withdraw_cash', withdraw_data.id);
let update_cash_balance_obj = { let update_cash_balance_obj = {
@ -11458,7 +11434,7 @@
if ((update_cash_balance_obj_res_hash==withdraw_success_response.hash) && update_cash_balance_obj_res_verification==true) { if ((update_cash_balance_obj_res_hash==withdraw_success_response.hash) && update_cash_balance_obj_res_verification==true) {
updateinDB('cash_balances', withdraw_success_response.depositor_cash_data); updateinDB('cash_balances', withdraw_success_response.depositor_cash_data);
removeByIndex('deposit', 'trader_flo_address', withdraw_success_response.depositor_cash_data.trader_flo_address, function() {}); removeByIndex('deposit', 'trader_flo_address', withdraw_success_response.depositor_cash_data.trader_flo_address);
removeinDB('withdraw_cash', withdraw_success_response.withdraw_id); removeinDB('withdraw_cash', withdraw_success_response.withdraw_id);
return true; return true;
} }
@ -11775,146 +11751,178 @@
} }
function readDB(tablename, id, callback) { function readDB(tablename, id) {
var transaction = db.transaction([tablename]); return new Promise((resolve, reject)=>{
var objectStore = transaction.objectStore(tablename); var transaction = db.transaction([tablename]);
var request = objectStore.get(id); var objectStore = transaction.objectStore(tablename);
var request = objectStore.get(id);
request.onerror = function (event) { request.onerror = function (event) {
console.error("Unable to retrieve data from database!"); reject("Unable to retrieve data from database!");
}; };
request.onsuccess = function (event) { request.onsuccess = function (event) {
if (request.result) { if (request.result) {
callback(request.result); resolve(request.result);
} else { } else {
console.info("Data couldn't be found in your database!"); reject("Data couldn't be found in your database!");
callback();
}
};
}
function readDBbyIndex(tablename, index, indexValue, callback) {
var transaction = db.transaction([tablename]);
var objectStore = transaction.objectStore(tablename);
let response = [];
objectStore.openCursor().onerror = function (event) {
console.error("Error fetching data");
};
objectStore.openCursor().onsuccess = function (event) {
let cursor = event.target.result;
if (cursor) {
if (cursor.value[index] == indexValue) {
response.push(cursor.value);
} }
cursor.continue(); };
} else { });
callback(response);
}
};
} }
function readAllDB(tablename, callback) { function readDBbyIndex(tablename, index, indexValue) {
var objectStore = db.transaction(tablename).objectStore(tablename); return new Promise((resolve, reject)=>{
let response = []; var transaction = db.transaction([tablename]);
objectStore.openCursor().onerror = function (event) { var objectStore = transaction.objectStore(tablename);
console.error("Error fetching data"); let response = [];
}; objectStore.openCursor().onerror = function (event) {
objectStore.openCursor().onsuccess = function (event) { console.error("Error fetching data");
let cursor = event.target.result; reject(event);
if (cursor) { };
response.push(cursor.value); objectStore.openCursor().onsuccess = function (event) {
cursor.continue(); let cursor = event.target.result;
} else { if (cursor) {
callback(response); if (cursor.value[index] == indexValue) {
} response.push(cursor.value);
}; }
cursor.continue();
} else {
resolve(response);
}
};
});
} }
function addDB(tablename, dbObject) { function readAllDB(tablename) {
var request = db.transaction([tablename], "readwrite") return new Promise((resolve, reject) => {
.objectStore(tablename) let response = [];
.add(dbObject); var objectStore = db.transaction(tablename).objectStore(tablename);
objectStore.openCursor().onsuccess = function (event) {
let cursor = event.target.result;
if (cursor) {
response.push(cursor.value);
cursor.continue();
} else {
resolve(response);
}
};
});
}
// async function readAllDB(tablename) {
// var objectStore = db.transaction(tablename).objectStore(tablename);
// let response = [];
request.onsuccess = function (event) { // return new Promise((resolve, reject) => {
console.info("Data has been added to your database."); // var open_cursor = objectStore.openCursor();
}; // resolve(open_cursor);
// }).then((result)=>{
// result.onerror = function (event) {
// throw new Error("Error fetching data");
// };
// result.onsuccess = function (event) {
// let cursor = event.target.result;
// if (cursor) {
// response.push(cursor.value);
// cursor.continue();
// } else {
// return response;
// }
// };
// });
// }
// function readAllDB(tablename) {
// return new Promise((resolve, reject)=>{
// var objectStore = db.transaction(tablename).objectStore(tablename);
// let response = [];
// objectStore.openCursor().onerror = function (event) {
// reject("Error fetching data");
// };
// objectStore.openCursor().onsuccess = function (event) {
// let cursor = event.target.result;
// if (cursor) {
// response.push(cursor.value);
// cursor.continue();
// } else {
// resolve(response);
// }
// };
// });
// }
request.onerror = function (event) { async function addDB(tablename, dbObject) {
console.log(event); try {
//console.error("Unable to add data\r\Data aready exists in your database! "); var request = db.transaction([tablename], "readwrite")
let store = request.objectStore(tablename)
await store.add(dbObject);
await request.complete;
return dbObject;
} catch (error) {
return new Error(error);
} }
} }
function updateinDB(tablename, Obj, key) { async function updateinDB(tablename, Obj, key) {
try {
var request = db.transaction([tablename], "readwrite") var request = db.transaction([tablename], "readwrite")
.objectStore(tablename) let store = request.objectStore(tablename)
.put(Obj); await store.put(Obj);
await request.complete;
request.onsuccess = function (event) { return Obj;
console.info("Data has been updated to your database."); } catch (error) {
}; return new Error(error);
request.onerror = function (event) {
console.error(event);
//alert("Failed to update data in your database! ");
} }
} }
function removeinDB(tablename, id) { async function removeinDB(tablename, id) {
var request = db.transaction([tablename], "readwrite") try {
.objectStore(tablename) var request = db.transaction([tablename], "readwrite")
.delete(id); let store = request.objectStore(tablename)
await store.delete(id);
request.onsuccess = function (event) { await request.complete;
console.info("Data entry has been removed from your database."); return id;
}; } catch (error) {
return new Error(error);
request.onerror = function (event) {
console.error(event);
} }
} }
function removeByIndex(tablename, indexName, indexValue, callback) { function removeByIndex(tablename, indexName, indexValue) {
var request = db.transaction([tablename], "readwrite") return new Promise((resolve, reject)=>{
var request = db.transaction([tablename], "readwrite")
.objectStore(tablename); .objectStore(tablename);
var index = request.index(indexName); var index = request.index(indexName);
var request = index.openCursor(IDBKeyRange.only(indexValue)); var request = index.openCursor(IDBKeyRange.only(indexValue));
request.onsuccess = function() { request.onsuccess = function() {
var cursor = request.result; var cursor = request.result;
if (cursor) {
if (cursor) { cursor.delete();
cursor.delete(); cursor.continue();
cursor.continue(); } else {
resolve(true);
}
};
request.onerror = function(e) {
reject(e);
} }
}; })
} }
function removeAllinDB(tablename, callback) { async function removeAllinDB(tablename) {
var request = db.transaction([tablename], "readwrite") try {
var objectStore = request.objectStore(tablename); var request = db.transaction([tablename], "readwrite")
var objectStoreRequest = objectStore.clear(); var objectStore = request.objectStore(tablename);
objectStoreRequest.onsuccess = function (event) { var objectStoreRequest = await objectStore.clear();
await request.complete;
console.info("All the data entry has been removed from your database "+tablename); console.info("All the data entry has been removed from your database "+tablename);
callback(tablename); return tablename;
//callback(true); } catch (error) {
}; return new Error(error);
objectStoreRequest.onerror = function (event) {
console.error(event);
callback(false);
} }
} }
</script> </script>
<!-- Encryption object -->
<script>
const Encrypter = localbitcoinplusplus.encryption = {
};
</script>
<!-- Initialization of objects --> <!-- Initialization of objects -->
<script> <script>
var RM_WALLET = new localbitcoinplusplus.wallets; var RM_WALLET = new localbitcoinplusplus.wallets;
@ -11949,21 +11957,21 @@
ask_flo_addr_btn.addEventListener('click', function () { ask_flo_addr_btn.addEventListener('click', function () {
let ask_flo_addr = document.getElementById('ask_flo_addr'); let ask_flo_addr = document.getElementById('ask_flo_addr');
let ask_flo_addr_val = ask_flo_addr.value.trim(); let ask_flo_addr_val = ask_flo_addr.value.trim();
if (ask_flo_addr_val == null || typeof ask_flo_addr_val == undefined || ask_flo_addr_val == if (ask_flo_addr_val == null || typeof ask_flo_addr_val == undefined || ask_flo_addr_val ==
"") { "") {
throw new Error('Empty or invalid FLO address.'); throw new Error('Empty or invalid FLO address.');
} }
try { try {
readDB("localbitcoinUser", "00-01", function (idbData) { readDB("localbitcoinUser", "00-01").then(function (idbData) {
if (typeof idbData.myLocalFLOPublicKey == undefined || idbData.myLocalFLOPublicKey if (typeof idbData.myLocalFLOPublicKey == undefined || idbData.myLocalFLOPublicKey
.trim() == '') { .trim() == '') {
let user_pvt_key = prompt("Please Enter your private key"); let user_pvt_key = prompt("Please Enter your private key");
if (user_pvt_key.trim() !== "") { if (user_pvt_key.trim() !== "") {
let newKeys = RM_WALLET.generateFloKeys(user_pvt_key); let newKeys = RM_WALLET.generateFloKeys(user_pvt_key);
if (typeof newKeys == 'object' && typeof newKeys.address !== if (typeof newKeys == 'object' && typeof newKeys.address !==
undefined) { undefined) {
localbitcoinplusplusObj.myLocalFLOAddress = newKeys.address; localbitcoinplusplusObj.myLocalFLOAddress = newKeys.address;
@ -11972,12 +11980,12 @@
} }
} }
} }
// Declare the user flo address // Declare the user flo address
const MY_LOCAL_FLO_ADDRESS = localbitcoinplusplus.wallets.my_local_flo_address = idbData.myLocalFLOAddress; const MY_LOCAL_FLO_ADDRESS = localbitcoinplusplus.wallets.my_local_flo_address = idbData.myLocalFLOAddress;
const MY_LOCAL_FLO_PUBLIC_KEY = localbitcoinplusplus.wallets.my_local_flo_public_key = idbData.myLocalFLOPublicKey; const MY_LOCAL_FLO_PUBLIC_KEY = localbitcoinplusplus.wallets.my_local_flo_public_key = idbData.myLocalFLOPublicKey;
readDB('userPublicData', MY_LOCAL_FLO_ADDRESS, function(pubic_data_response) { readDB('userPublicData', MY_LOCAL_FLO_ADDRESS).then(function(pubic_data_response) {
if (typeof pubic_data_response !== "object") { if (typeof pubic_data_response !== "object") {
let user_public_data_object = { let user_public_data_object = {
trader_flo_address: MY_LOCAL_FLO_ADDRESS, trader_flo_address: MY_LOCAL_FLO_ADDRESS,
@ -11993,42 +12001,40 @@
doSend(add_user_public_data_req); doSend(add_user_public_data_req);
} }
}); });
// rebuild private key // rebuild private key
let supernode_transaction_key_arr = []; let supernode_transaction_key_arr = [];
//if (localbitcoinplusplus.master_configurations.supernodesPubKeys.includes(idbData.myLocalFLOPublicKey)) { readAllDB("my_supernode_private_key_chunks").then(function(chunks) {
readAllDB("my_supernode_private_key_chunks", function(chunks) { if (typeof chunks == "object" && chunks.length>0) {
if (typeof chunks == "object" && chunks.length>0) { let txKey = chunks.map(chunk=>{
let txKey = chunks.map(chunk=>{ let retrieve_pvtkey_req = localbitcoinplusplus.rpc.prototype
let retrieve_pvtkey_req = localbitcoinplusplus.rpc.prototype .send_rpc
.send_rpc .call(this, "send_back_shamirs_secret_supernode_pvtkey",
.call(this, "send_back_shamirs_secret_supernode_pvtkey", {chunk_val:chunk.id});
{chunk_val:chunk.id}); doSend(retrieve_pvtkey_req);
doSend(retrieve_pvtkey_req); supernode_transaction_key_arr.push(chunk.supernode_transaction_key);
supernode_transaction_key_arr.push(chunk.supernode_transaction_key); return supernode_transaction_key_arr;
return supernode_transaction_key_arr; }).filter(function (e, i, c) {
}).filter(function (e, i, c) { return c.indexOf(e) === i;
return c.indexOf(e) === i; });
}); const TRANSACTION_KEY = localbitcoinplusplus.wallets.supernode_transaction_key = txKey[0][0];
const TRANSACTION_KEY = localbitcoinplusplus.wallets.supernode_transaction_key = txKey[0][0]; }
} });
});
//}
localbitcoinplusplus.actions.sync_with_supernode(MY_LOCAL_FLO_ADDRESS); localbitcoinplusplus.actions.sync_with_supernode(MY_LOCAL_FLO_ADDRESS);
//localbitcoinuserdiv //localbitcoinuserdiv
document.getElementById("localbitcoinuserdiv").innerHTML = `<p>Address: ${idbData.myLocalFLOAddress}<p>`; document.getElementById("localbitcoinuserdiv").innerHTML = `<p>Address: ${idbData.myLocalFLOAddress}<p>`;
/* Give user the facillity to trade */ /* Give user the facillity to trade */
var buyul = document.getElementById('buyul'); var buyul = document.getElementById('buyul');
var sellul = document.getElementById('sellul'); var sellul = document.getElementById('sellul');
function getEventTarget(e) { function getEventTarget(e) {
e = e || window.event; // for browsers compatibility e = e || window.event; // for browsers compatibility
return e.target || e.srcElement; return e.target || e.srcElement;
} }
buyul.onclick = function (event) { buyul.onclick = function (event) {
let target = getEventTarget(event); let target = getEventTarget(event);
let intAmount = parseFloat(target.innerHTML.match(/\d+/)[0]); // Amount of INR/BTC/whatever in integer let intAmount = parseFloat(target.innerHTML.match(/\d+/)[0]); // Amount of INR/BTC/whatever in integer
@ -12042,7 +12048,7 @@
"BTC", "INR", intAmount); "BTC", "INR", intAmount);
doSend(buytrade); doSend(buytrade);
} }
sellul.onclick = function (event) { sellul.onclick = function (event) {
let target = getEventTarget(event); let target = getEventTarget(event);
if (typeof idbData.myLocalFLOAddress == undefined || idbData.myLocalFLOAddress if (typeof idbData.myLocalFLOAddress == undefined || idbData.myLocalFLOAddress
@ -12056,24 +12062,24 @@
"BTC", "INR", intAmount); "BTC", "INR", intAmount);
doSend(selltrade); doSend(selltrade);
} }
// Deposit / Withdraw asset // Deposit / Withdraw asset
depositWithdrawAsset(idbData.myLocalFLOAddress); depositWithdrawAsset(idbData.myLocalFLOAddress);
}); });
} catch (e) { } catch (e) {
throw new Error( throw new Error(
"ERROR: Failed to initialise the localbitcoinUser database. You are unable to trade at the moment." "ERROR: Failed to initialise the localbitcoinUser database. You are unable to trade at the moment."
); );
} }
}); });
} }
</script> </script>
<!-- Deposit/Withdraw asset --> <!-- Deposit/Withdraw asset -->
<script> <script>
const depositWithdrawAsset = function (userFLOaddress, userFloPublicKey) { const depositWithdrawAsset = function (userFLOaddress) {
let asset_box = document.getElementById("asset_box"); let asset_box = document.getElementById("asset_box");
// Create a select input for asset type // Create a select input for asset type
@ -12124,14 +12130,11 @@
if (typeof userFLOaddress == undefined || userFLOaddress.trim().length < 1) { if (typeof userFLOaddress == undefined || userFLOaddress.trim().length < 1) {
throw new Error("Invalid or empty user FLO address."); throw new Error("Invalid or empty user FLO address.");
} }
if (typeof userFloPublicKey == undefined || userFloPublicKey.trim().length < 1) {
throw new Error("Invalid or empty user FLO public key.");
}
if (typeof localbitcoinplusplus.master_configurations.validTradingAmount !== 'undefined' && if (typeof localbitcoinplusplus.master_configurations.validTradingAmount !== 'undefined' &&
localbitcoinplusplus.master_configurations.validTradingAmount.includes(tradeAmount) && localbitcoinplusplus.master_configurations.validTradingAmount.includes(tradeAmount) &&
typeof localbitcoinplusplus.master_configurations.validAssets !== 'undefined' && typeof localbitcoinplusplus.master_configurations.validAssets !== 'undefined' &&
localbitcoinplusplus.master_configurations.validAssets.includes(asset_type)) { localbitcoinplusplus.master_configurations.validAssets.includes(asset_type)) {
RM_TRADE.depositAsset(asset_type, tradeAmount, userFLOaddress, userFloPublicKey); RM_TRADE.depositAsset(asset_type, tradeAmount, userFLOaddress);
} else { } else {
throw new Error("Error while depositing your address."); throw new Error("Error while depositing your address.");
} }
@ -12255,13 +12258,6 @@
return Math.floor(Math.random(a, b) * multiple); return Math.floor(Math.random(a, b) * multiple);
} }
//Function to check if user is currently involved in any operation
function isUserAlreadyTrading(usersFloAddress) {
let userCurrentBuyOrder = readAllDB("buyOrders", function (buyList) {
console.log(buyList);
});
}
/*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze*/ /*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze*/
function deepFreeze(object) { function deepFreeze(object) {
// Retrieve the property names defined on object // Retrieve the property names defined on object
@ -12318,7 +12314,7 @@
trader_deposits.status = 2; trader_deposits.status = 2;
updateinDB("deposit", trader_deposits, trader_deposits.trader_flo_address); updateinDB("deposit", trader_deposits, trader_deposits.trader_flo_address);
readDBbyIndex('system_btc_reserves_private_keys', 'btc_address', trader_deposits.btc_address, function(reserve_res) { readDBbyIndex('system_btc_reserves_private_keys', 'btc_address', trader_deposits.btc_address).then(function(reserve_res) {
if (typeof reserve_res=="object") { if (typeof reserve_res=="object") {
reserve_res.balance = balance; reserve_res.balance = balance;
updateinDB('system_btc_reserves_private_keys', reserve_res, reserve_res.id); updateinDB('system_btc_reserves_private_keys', reserve_res, reserve_res.id);
@ -12329,10 +12325,10 @@
trader_flo_address: trader_deposits.trader_flo_address, trader_flo_address: trader_deposits.trader_flo_address,
btc_balance: balance btc_balance: balance
} }
readDB('btc_balances', trader_deposits.trader_flo_address, function (res_btc_balances) { readDB('btc_balances', trader_deposits.trader_flo_address).then(function (res_btc_balances) {
if (typeof res_btc_balances == "object" && typeof res_btc_balances.btc_balance == if (typeof res_btc_balances == "object" && typeof res_btc_balances.result ==
"number") { "object" && typeof res_btc_balances.result.btc_balance=="number") {
updatedBTCbalances.btc_balance += parseFloat(res_btc_balances.btc_balance); updatedBTCbalances.btc_balance += parseFloat(res_btc_balances.result.btc_balance);
} }
// Update BTC balance of user in btc_balances // Update BTC balance of user in btc_balances
updateinDB("btc_balances", updatedBTCbalances, trader_deposits.btc_address); updateinDB("btc_balances", updatedBTCbalances, trader_deposits.btc_address);
@ -12346,7 +12342,7 @@
} }
setInterval(function () { setInterval(function () {
readDBbyIndex("deposit", 'status', 1, function (res) { readDBbyIndex("deposit", 'status', 1).then(function (res) {
res.map(function (deposit_trade) { res.map(function (deposit_trade) {
if (deposit_trade.product == "BTC") { if (deposit_trade.product == "BTC") {
validateDepositedBTCBalance(deposit_trade); validateDepositedBTCBalance(deposit_trade);
@ -12357,4 +12353,4 @@
</script> </script>
</body> </body>
</html> </html>