diff --git a/supernode/index.html b/supernode/index.html index 83c134d..aa03b50 100644 --- a/supernode/index.html +++ b/supernode/index.html @@ -9,11 +9,11 @@
-

Local Bitcoin Plus Plus P2P EXCHANGE

- + +

Local Bitcoin Plus Plus P2P EXCHANGE

+
+ - +

FLO ID:

-

+
- Lorem ipsum dolor sit amet, consectetur adipisicing elit. + Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam, ipsum recusandae voluptatibus mollitia quidem.
@@ -335,7 +383,7 @@
DEPOSIT WITHDRAW ASSET
- +
@@ -349,6 +397,7 @@
+
@@ -361,30 +410,13 @@
-
-
- -
-
    -
    +
    -
    @@ -392,17 +424,25 @@
    - +
    + - - + //Defining Elliptic Encryption Object + var ellipticEncryption = window.ellipticCurveEncryption = function () {}; + + ellipticEncryption.rng = new SecureRandom(); + + + + ellipticEncryption.getCurveParameters = function (curveName) { + + //Default is secp256k1 + curveName = typeof curveName !== 'undefined' ? curveName : "secp256k1"; + + var c = EllipticCurve.getSECCurveByName(curveName); + var curveDetails = { + Q: "", + A: "", + B: "", + GX: "", + GY: "", + N: "" + }; + + curveDetails.Q = c.getCurve().getQ().toString(); + curveDetails.A = c.getCurve().getA().toBigInteger().toString(); + curveDetails.B = c.getCurve().getB().toBigInteger().toString(); + curveDetails.GX = c.getG().getX().toBigInteger().toString(); + curveDetails.GY = c.getG().getY().toBigInteger().toString(); + curveDetails.N = c.getN().toString(); + + return curveDetails; + + } + + ellipticEncryption.selectedCurve = ellipticEncryption.getCurveParameters(ellipticCurveType); + + + ellipticEncryption.get_curve = function () { + return new EllipticCurve.CurveFp(new BigInteger(this.selectedCurve.Q), + new BigInteger(this.selectedCurve.A), + new BigInteger(this.selectedCurve.B)); + } + + ellipticEncryption.get_G = function (curve) { + return new EllipticCurve.PointFp(curve, + curve.fromBigInteger(new BigInteger(this.selectedCurve.GX)), + curve.fromBigInteger(new BigInteger(this.selectedCurve.GY))); + } + + + ellipticEncryption.pick_rand = function () { + var n = new BigInteger(this.selectedCurve.N); + var n1 = n.subtract(BigInteger.ONE); + var r = new BigInteger(n.bitLength(), this.rng); + return r.mod(n1).add(BigInteger.ONE); + } + + + ellipticEncryption.senderRandom = function () { + var r = this.pick_rand(); + return r.toString(); + }; + + + + ellipticEncryption.receiverRandom = function () { + + //This is receivers private key. For now we will use random. CHANGE IT LATER + var r = this.pick_rand(); + return r.toString(); + } + + + + ellipticEncryption.senderPublicString = function (senderPrivateKey) { + + var senderKeyECData = {}; + + var curve = this.get_curve(); + var G = this.get_G(curve); + var a = new BigInteger(senderPrivateKey); + var P = G.multiply(a); + senderKeyECData.XValuePublicString = P.getX().toBigInteger().toString(); + senderKeyECData.YValuePublicString = P.getY().toBigInteger().toString(); + + return senderKeyECData; + } + + //In real life ellipticEncryption.receiverPublicString is the public key of the receiver. + //you don't have to run receiverRandom and the bottom function + ellipticEncryption.receiverPublicString = function (receiverPublicKey) { + + var receiverKeyECData = {}; + + var curve = this.get_curve(); + var G = this.get_G(curve); + var a = new BigInteger(receiverPublicKey); + var P = G.multiply(a); + receiverKeyECData.XValuePublicString = P.getX().toBigInteger().toString(); + receiverKeyECData.YValuePublicString = P.getY().toBigInteger().toString(); + + return receiverKeyECData; + } + + ellipticEncryption.senderSharedKeyDerivation = function (receiverPublicStringXValue, + receiverPublicStringYValue, senderPrivateKey) { + + var senderDerivedKey = {}; + var curve = this.get_curve(); + var P = new EllipticCurve.PointFp(curve, + curve.fromBigInteger(new BigInteger(receiverPublicStringXValue)), + curve.fromBigInteger(new BigInteger(receiverPublicStringYValue))); + var a = new BigInteger(senderPrivateKey); + var S = P.multiply(a); + + senderDerivedKey.XValue = S.getX().toBigInteger().toString(); + senderDerivedKey.YValue = S.getY().toBigInteger().toString(); + + return senderDerivedKey; + } + + + ellipticEncryption.receiverSharedKeyDerivation = function (senderPublicStringXValue, + senderPublicStringYValue, receiverPrivateKey) { + + var receiverDerivedKey = {}; + var curve = this.get_curve(); + var P = new EllipticCurve.PointFp(curve, + curve.fromBigInteger(new BigInteger(senderPublicStringXValue)), + curve.fromBigInteger(new BigInteger(senderPublicStringYValue))); + var a = new BigInteger(receiverPrivateKey); + var S = P.multiply(a); + + receiverDerivedKey.XValue = S.getX().toBigInteger().toString(); + receiverDerivedKey.YValue = S.getY().toBigInteger().toString(); + + return receiverDerivedKey; + } + + })("secp256k1"); // End of EllipticCurveEncryption Object + - @@ -35623,8 +36916,8 @@ exports.createContext = Script.createContext = function (context) { }, filter_legit_requests: function (callback) { - if (typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY === "string" - && localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY.length > 0 + if (typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY === "string" && + localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY.length > 0 ) { const RM_WALLET = new localbitcoinplusplus.wallets; let user_keys = RM_WALLET.generateFloKeys(localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY); @@ -35633,7 +36926,7 @@ exports.createContext = Script.createContext = function (context) { user_keys.pubKeyHex)) { return callback(true); } - } + } } return callback(false); }, @@ -35644,104 +36937,125 @@ exports.createContext = Script.createContext = function (context) { var method = request.method; if (typeof params == "object" && typeof method == "string") { - + const RM_WALLET = new localbitcoinplusplus.wallets; const RM_TRADE = new localbitcoinplusplus.trade; const RM_RPC = new localbitcoinplusplus.rpc; - + let respective_trader_id = ''; if (typeof params.trader_flo_address == "string") respective_trader_id = params.trader_flo_address; request.response = {}; - if(localbitcoinplusplus.master_configurations.supernodesPubKeys.includes(localbitcoinplusplus.wallets.my_local_flo_public_key)) { + if (localbitcoinplusplus.master_configurations.supernodesPubKeys.includes( + localbitcoinplusplus.wallets.my_local_flo_public_key)) { try { - // CHECK HERE IF USER IS INDULGED IN ANY MORE TRADE. IF TRUE RETURN ERROR - await readAllDB("deposit").then(function(res) { - if (typeof res == "object" && res.length>0) { - let canUserTrade = res.map(function(user) { - return respective_trader_id == user.trader_flo_address; - }); - if (canUserTrade.includes(true)) { - request.response = `Trader id ${respective_trader_id} is not clear for trade currently. + // CHECK HERE IF USER IS INDULGED IN ANY MORE TRADE. IF TRUE RETURN ERROR + await readAllDB("deposit").then(function (res) { + if (typeof res == "object" && res.length > 0) { + let canUserTrade = res.map(function (user) { + return respective_trader_id == user.trader_flo_address; + }); + if (canUserTrade.includes(true)) { + 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.`; - return false; + return false; + } } - } - }); + }); - // Check if user id is in deposit or withdraw. If true prevent him from trading - await readAllDB('withdraw_cash').then(function(res) { - if (typeof res=="object") { - let check_deposit_withdraw_id_array = res.filter(f=>f.status===2) - .map(m=>{ - if (m.trader_flo_address==respective_trader_id||m.deposit_withdraw_id_array==respective_trader_id) { - let server_msg = `Trader id ${respective_trader_id} is not clear for trade currently. + // Check if user id is in deposit or withdraw. If true prevent him from trading + await readAllDB('withdraw_cash').then(function (res) { + if (typeof res == "object") { + let check_deposit_withdraw_id_array = res.filter(f => f.status === + 2) + .map(m => { + if (m.trader_flo_address == respective_trader_id || m.deposit_withdraw_id_array == + respective_trader_id) { + 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.`; - const RM_RPC = new localbitcoinplusplus.rpc; - let server_response = RM_RPC - .send_rpc - .call(this, "supernode_message", - {"trader_flo_id":respective_trader_id, "server_msg":server_msg}); - doSend(server_response); - throw new Error("User has not finished previous pending actions."); - } - }); + const RM_RPC = new localbitcoinplusplus.rpc; + let server_response = RM_RPC + .send_rpc + .call(this, "supernode_message", { + "trader_flo_id": respective_trader_id, + "server_msg": server_msg + }); + doSend(server_response); + throw new Error( + "User has not finished previous pending actions." + ); + } + }); } }); } catch (error) { throw new Error(error); } } - + switch (method) { case "trade_buy": - + RM_RPC.filter_legit_requests(async function (is_valid_request) { if (is_valid_request !== true) return false; - await RM_TRADE.resolve_current_crypto_price_in_fiat(params.product, params.currency); - let trade_margin = await RM_TRADE.getAssetTradeAndWithdrawLimit(params.trader_flo_address, params.product, params.currency); - if (typeof trade_margin.remaining_crypto_credit=="number" && typeof trade_margin.remaining_fiat_credit=="number") { - if (trade_margin.remaining_fiat_credit>0 && trade_margin.remaining_fiat_credit>=params.buy_price) { + await RM_TRADE.resolve_current_crypto_price_in_fiat(params.product, + params.currency); + let trade_margin = await RM_TRADE.getAssetTradeAndWithdrawLimit( + params.trader_flo_address, params.product, params.currency); + if (typeof trade_margin.remaining_crypto_credit == "number" && + typeof trade_margin.remaining_fiat_credit == "number") { + if (trade_margin.remaining_fiat_credit > 0 && trade_margin.remaining_fiat_credit >= + params.buy_price) { request.response = RM_TRADE.trade_buy.call(this, - ...request.params, - function (supernode_signed_res) { - if (typeof supernode_signed_res == "object") { - let buy_request_response = RM_RPC - .send_rpc - .call(this, "trade_buy_request_response", - supernode_signed_res); - doSend(buy_request_response); - // Init trading - RM_TRADE.createTradePipes(params.currency); - return true; - } - }); + ...request.params, + function (supernode_signed_res) { + if (typeof supernode_signed_res == "object") { + let buy_request_response = RM_RPC + .send_rpc + .call(this, + "trade_buy_request_response", + supernode_signed_res); + doSend(buy_request_response); + // Init trading + RM_TRADE.createTradePipes(params.currency); + return true; + } + }); } else { - throw new Error(`Trade Margin Check Failed: You can only trade upto ${params.currency} ${trade_margin.remaining_fiat_credit}.`); + throw new Error( + `Trade Margin Check Failed: You can only trade upto ${params.currency} ${trade_margin.remaining_fiat_credit}.` + ); } } else { throw new Error("Invalid trade margin figures."); } - + }); break; case "trade_sell": RM_RPC.filter_legit_requests(async function (is_valid_request) { if (is_valid_request !== true) return false; - await RM_TRADE.resolve_current_crypto_price_in_fiat(params.product, params.currency); - let trade_margin = await RM_TRADE.getAssetTradeAndWithdrawLimit(params.trader_flo_address, params.product, params.currency); - if (typeof trade_margin.remaining_crypto_credit=="number" && typeof trade_margin.remaining_fiat_credit=="number") { + await RM_TRADE.resolve_current_crypto_price_in_fiat(params.product, + params.currency); + let trade_margin = await RM_TRADE.getAssetTradeAndWithdrawLimit( + params.trader_flo_address, params.product, params.currency); + if (typeof trade_margin.remaining_crypto_credit == "number" && + typeof trade_margin.remaining_fiat_credit == "number") { let eqCrypto = RM_TRADE.calculateCryptoEquivalentOfCash(params.buy_price); - if (trade_margin.remaining_crypto_credit>0 && trade_margin.remaining_crypto_credit>=eqCrypto) { + if (trade_margin.remaining_crypto_credit > 0 && trade_margin.remaining_crypto_credit >= + eqCrypto) { request.response = RM_TRADE.trade_sell.call( this, ...request.params, function (supernode_signed_res) { if (typeof supernode_signed_res == "object") { let sell_request_response = RM_RPC .send_rpc - .call(this, "trade_sell_request_response", + .call(this, + "trade_sell_request_response", supernode_signed_res); doSend(sell_request_response); // Init trading @@ -35749,9 +37063,11 @@ exports.createContext = Script.createContext = function (context) { return true; } } - ); + ); } else { - throw new Error(`Trade Margin Check Failed: You can only trade upto ${params.currency} ${trade_margin.remaining_fiat_credit}.`); + throw new Error( + `Trade Margin Check Failed: You can only trade upto ${params.currency} ${trade_margin.remaining_fiat_credit}.` + ); } } else { throw new Error("Invalid trade margin figures."); @@ -35760,19 +37076,24 @@ exports.createContext = Script.createContext = function (context) { break; case "sync_with_supernode": RM_RPC.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) { - const tableArray = ["deposit", "withdraw_cash", "withdraw_btc", "crypto_balances", "cash_balances", "userPublicData"]; - localbitcoinplusplus.actions.get_sharable_db_data(tableArray).then(function(su_db_data) { - if (typeof su_db_data == "object") { - su_db_data.trader_flo_address = params.trader_flo_address; - let server_sync_response = RM_RPC - .send_rpc - .call(this, "server_sync_response", - su_db_data); - doSend(server_sync_response); - return; - } - }); + if (is_valid_request === true && params.job == + "SYNC_MY_LOCAL_DB_WITH_SUPERNODE_DB" && params.trader_flo_address.length > + 0) { + const tableArray = ["deposit", "withdraw_cash", "withdraw_btc", + "crypto_balances", "cash_balances", "userPublicData" + ]; + localbitcoinplusplus.actions.get_sharable_db_data(tableArray).then( + function (su_db_data) { + if (typeof su_db_data == "object") { + su_db_data.trader_flo_address = params.trader_flo_address; + let server_sync_response = RM_RPC + .send_rpc + .call(this, "server_sync_response", + su_db_data); + doSend(server_sync_response); + return; + } + }); } }); break; @@ -35780,201 +37101,406 @@ exports.createContext = Script.createContext = function (context) { RM_RPC.filter_legit_requests(function (is_valid_request) { if (is_valid_request !== true) return false; - + // This code will only run for supernodes - if (typeof params.product !== "undefined" - && (localbitcoinplusplus.master_configurations.tradableAsset1.includes(params.product) - || localbitcoinplusplus.master_configurations.tradableAsset2.includes(params.product)) - && typeof params.depositing_amount !== "undefined" - && localbitcoinplusplus.master_configurations.tradableAsset2.includes(params.currency) - && typeof localbitcoinplusplus.master_configurations.validTradingAmount !== 'undefined' - && localbitcoinplusplus.master_configurations.validTradingAmount.includes(parseFloat(params.depositing_amount)) - && typeof params.trader_flo_address == "string" - && params.trader_flo_address.length > 0 + if (typeof params.product !== "undefined" && + (localbitcoinplusplus.master_configurations.tradableAsset1.includes( + params.product) || + localbitcoinplusplus.master_configurations.tradableAsset2.includes( + params.product)) && + typeof params.depositing_amount !== "undefined" && + localbitcoinplusplus.master_configurations.tradableAsset2.includes( + params.currency) && + typeof localbitcoinplusplus.master_configurations.validTradingAmount !== + 'undefined' && + localbitcoinplusplus.master_configurations.validTradingAmount.includes( + parseFloat(params.depositing_amount)) && + typeof params.trader_flo_address == "string" && + params.trader_flo_address.length > 0 ) { - RM_WALLET.getUserPublicKey(params.trader_flo_address, - async function(requester_public_key) { - if (requester_public_key==undefined||requester_public_key==null) { - throw new Error('Failed to get public key of the user.'); - } - params.depositor_public_key = requester_public_key; + RM_WALLET.getUserPublicKey(params.trader_flo_address, + async function (requester_public_key) { + if (requester_public_key == undefined || + requester_public_key == null) { + throw new Error( + 'Failed to get public key of the user.' + ); + } + params.depositor_public_key = requester_public_key; - await RM_TRADE.resolve_current_crypto_price_in_fiat(params.product, params.currency); + await RM_TRADE.resolve_current_crypto_price_in_fiat( + params.product, params.currency); - if (localbitcoinplusplus.master_configurations.tradableAsset1.includes(params.product)) { - - let generate_btc_keys_for_requester = RM_WALLET - .generateFloKeys(null, params.product); + if (localbitcoinplusplus.master_configurations.tradableAsset1 + .includes(params.product)) { - params.id = helper_functions.unique_id(); - params.status = 1; - params.btc_address = generate_btc_keys_for_requester.address; + let generate_btc_keys_for_requester = RM_WALLET + .generateFloKeys(null, params.product); - params.bitcoinToBePaid = RM_TRADE.calculateCryptoEquivalentOfCash( - params.depositing_amount, params.currency, params.product); + params.id = helper_functions.unique_id(); + params.status = 1; + params.btc_address = + generate_btc_keys_for_requester.address; - let receivedTradeInfo = {...params}; + params.bitcoinToBePaid = RM_TRADE.calculateCryptoEquivalentOfCash( + params.depositing_amount, params.currency, + params.product); - if (typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY=="undefined") { - throw new Error('Failed to determine Super node signing key.'); - } + let receivedTradeInfo = { + ...params + }; - readDB("localbitcoinUser", "00-01").then(function (su_data) { - if (typeof su_data == "object" && typeof su_data.myLocalFLOPublicKey == - "string" && - su_data.myLocalFLOPublicKey.length > 0 && - localbitcoinplusplus.master_configurations.supernodesPubKeys - .includes(su_data.myLocalFLOPublicKey)) { - - let receivedTradeInfoHash = Crypto.SHA256(JSON.stringify( - receivedTradeInfo)); - - receivedTradeInfo["depositDataHash"] = - receivedTradeInfoHash; - receivedTradeInfo["order_validator_sign"] = - RM_WALLET.sign( - receivedTradeInfoHash, localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY + if (typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY == + "undefined") { + throw new Error( + 'Failed to determine Super node signing key.' ); - receivedTradeInfo["order_validator_public_key"] = - su_data.myLocalFLOPublicKey; + } - try { - const this_btc_pvt_key = generate_btc_keys_for_requester.privateKeyWIF; - const this_btc_tx_key = Crypto.util.randomBytes(64); - const this_btc_pvt_key_shamirs_secret = RM_WALLET.createShamirsSecretShares(this_btc_pvt_key, 10, 5); - if (typeof this_btc_pvt_key_shamirs_secret=="object" && this_btc_pvt_key_shamirs_secret.length>0) { - addDB("deposit", receivedTradeInfo); + readDB("localbitcoinUser", "00-01").then( + function (su_data) { + if (typeof su_data == "object" && + typeof su_data.myLocalFLOPublicKey == + "string" && + su_data.myLocalFLOPublicKey.length > + 0 && + localbitcoinplusplus.master_configurations + .supernodesPubKeys + .includes(su_data.myLocalFLOPublicKey) + ) { - // Send the address to the requester - let deposit_response_object = { - error: false, - method: "deposit_asset_request_response", - msg: `Please send ${params.product} ${params.bitcoinToBePaid} to the following addres: ${generate_btc_keys_for_requester.address}.`, - data: receivedTradeInfo - }; - let deposit_request_response = RM_RPC - .send_rpc - .call(this, - "deposit_asset_request_response", - deposit_response_object); - doSend(deposit_request_response); + let receivedTradeInfoHash = + Crypto.SHA256(JSON.stringify( + receivedTradeInfo)); - let this_btc_pvt_key_shamirs_secret_array = this_btc_pvt_key_shamirs_secret.map(chunks=>{ - let chunk_ids = Crypto.util.bytesToHex(Crypto.util.randomBytes(64)); - let chunk_array = { - "id": chunk_ids, - "privateKeyChunks": Crypto.AES.encrypt(chunks, this_btc_tx_key) - }; - return chunk_array; - }); + receivedTradeInfo[ + "depositDataHash"] = + receivedTradeInfoHash; + receivedTradeInfo[ + "order_validator_sign"] = + RM_WALLET.sign( + receivedTradeInfoHash, + localbitcoinplusplus.wallets + .MY_SUPERNODE_PRIVATE_KEY + ); + receivedTradeInfo[ + "order_validator_public_key" + ] = + su_data.myLocalFLOPublicKey; - // Send chunks of private keys to other supernodes - this_btc_pvt_key_shamirs_secret_array.map(shares=>{ - let store_pvtkey_req = RM_RPC - .send_rpc - .call(this, "store_shamirs_secret_pvtkey_shares", shares); - doSend(store_pvtkey_req); - } - ); - - if (typeof localbitcoinplusplus.wallets.my_local_flo_address == "string" - && typeof localbitcoinplusplus.wallets.my_local_flo_public_key == "string" - && typeof localbitcoinplusplus.master_configurations.supernodesPubKeys == "object" - && localbitcoinplusplus.master_configurations.supernodesPubKeys.includes(localbitcoinplusplus.wallets.my_local_flo_public_key)) { try { - let this_btc_pvt_key_shamirs_secret__id_array = this_btc_pvt_key_shamirs_secret_array.map(i=>i.id); - let btc_private_key_shamirs_id = this_btc_pvt_key_shamirs_secret__id_array; - let supernode_transaction_key = this_btc_tx_key; - const system_btc_reserves_private_keys_object = { - id: helper_functions.unique_id(), - product: params.product, - btc_address: params.btc_address, - balance: null, - trader_flo_address: params.trader_flo_address, - btc_private_key_shamirs_id: btc_private_key_shamirs_id, - supernode_transaction_key: supernode_transaction_key + const this_btc_pvt_key = + generate_btc_keys_for_requester + .privateKeyWIF; + const this_btc_tx_key = + Crypto.util.randomBytes( + 64); + const + this_btc_pvt_key_shamirs_secret = + RM_WALLET.createShamirsSecretShares( + this_btc_pvt_key, + 10, 5); + if (typeof this_btc_pvt_key_shamirs_secret == + "object" && + this_btc_pvt_key_shamirs_secret + .length > 0) { + addDB("deposit", + receivedTradeInfo + ); + + // Send the address to the requester + let + deposit_response_object = { + error: false, + method: "deposit_asset_request_response", + msg: `Please send ${params.product} ${params.bitcoinToBePaid} to the following addres: ${generate_btc_keys_for_requester.address}.`, + data: receivedTradeInfo + }; + let + deposit_request_response = + RM_RPC + .send_rpc + .call(this, + "deposit_asset_request_response", + deposit_response_object + ); + doSend( + deposit_request_response + ); + + let + this_btc_pvt_key_shamirs_secret_array = + this_btc_pvt_key_shamirs_secret + .map(chunks => { + let + chunk_ids = + Crypto.util + .bytesToHex( + Crypto + .util + .randomBytes( + 64 + )); + let + chunk_array = { + "id": chunk_ids, + "privateKeyChunks": Crypto + .AES + .encrypt( + chunks, + this_btc_tx_key + ) + }; + return chunk_array; + }); + + // Send chunks of private keys to other supernodes + this_btc_pvt_key_shamirs_secret_array + .map(shares => { + let + store_pvtkey_req = + RM_RPC + .send_rpc + .call( + this, + "store_shamirs_secret_pvtkey_shares", + shares + ); + doSend( + store_pvtkey_req + ); + }); + + if (typeof localbitcoinplusplus + .wallets.my_local_flo_address == + "string" && + typeof localbitcoinplusplus + .wallets.my_local_flo_public_key == + "string" && + typeof localbitcoinplusplus + .master_configurations + .supernodesPubKeys == + "object" && + localbitcoinplusplus + .master_configurations + .supernodesPubKeys.includes( + localbitcoinplusplus + .wallets.my_local_flo_public_key + )) { + try { + let + this_btc_pvt_key_shamirs_secret__id_array = + this_btc_pvt_key_shamirs_secret_array + .map(i => i + .id); + let + btc_private_key_shamirs_id = + this_btc_pvt_key_shamirs_secret__id_array; + let + supernode_transaction_key = + this_btc_tx_key; + const + system_btc_reserves_private_keys_object = { + id: helper_functions + .unique_id(), + product: params + .product, + btc_address: params + .btc_address, + balance: null, + trader_flo_address: params + .trader_flo_address, + btc_private_key_shamirs_id: btc_private_key_shamirs_id, + supernode_transaction_key: supernode_transaction_key + } + addDB( + "system_btc_reserves_private_keys", + system_btc_reserves_private_keys_object + ); + } catch (error) { + throw new Error( + error); + } + } + return true; } - addDB("system_btc_reserves_private_keys", system_btc_reserves_private_keys_object); } catch (error) { throw new Error(error); } - } - return true; - } - } catch (error) { - throw new Error(error); - } - // Send the address to the requester - let deposit_response_object = { - error: false, - method: "deposit_asset_request_response", - msg: `Please send the ${params.product} to ${generate_btc_keys_for_requester.address}.`, - data: receivedTradeInfo + // Send the address to the requester + let deposit_response_object = { + error: false, + method: "deposit_asset_request_response", + msg: `Please send the ${params.product} to ${generate_btc_keys_for_requester.address}.`, + data: receivedTradeInfo + }; + + let deposit_request_response = + RM_RPC.send_rpc + .call(this, + "deposit_asset_request_response", + deposit_response_object + ); + doSend(deposit_request_response); + return true; + } + }); + + return false; + + } else if (!localbitcoinplusplus.master_configurations + .tradableAsset1.includes(params.product)) { + params.id = helper_functions.unique_id(); + params.status = 1; + // IMPORTANT - If deposit is a fiat make sure product and currency are both same + params.currency = params.product; + let receivedTradeInfo = { + ...params }; - let deposit_request_response = RM_RPC.send_rpc - .call(this, - "deposit_asset_request_response", - deposit_response_object); - doSend(deposit_request_response); - return true; - } - }); + readDB("localbitcoinUser", "00-01").then( + function (su_data) { + if (typeof su_data == "object" && + typeof su_data.myLocalFLOPublicKey == + "string" && + su_data.myLocalFLOPublicKey.length > + 0 && + localbitcoinplusplus.master_configurations + .supernodesPubKeys + .includes(su_data.myLocalFLOPublicKey) + ) { + let receivedTradeInfoHash = + Crypto.SHA256(JSON.stringify( + receivedTradeInfo)); - return false; + receivedTradeInfo[ + "depositDataHash"] = + receivedTradeInfoHash; + receivedTradeInfo[ + "order_validator_sign"] = + RM_WALLET.sign( + receivedTradeInfoHash, + localbitcoinplusplus.wallets + .MY_SUPERNODE_PRIVATE_KEY + ); + receivedTradeInfo[ + "order_validator_public_key" + ] = su_data.myLocalFLOPublicKey; - } else if (!localbitcoinplusplus.master_configurations.tradableAsset1.includes(params.product)) { - params.id = helper_functions.unique_id(); - params.status = 1; - // IMPORTANT - If deposit is a fiat make sure product and currency are both same - params.currency = params.product; - let receivedTradeInfo = { ...params }; + // YOU NEED TO DETERMINE A BANK ACCOUNT HERE IF NO ONE IS WITHDRAWING + try { + addDB("deposit", + receivedTradeInfo); + readDBbyIndex( + "withdraw_cash", + "status", 1).then( + function ( + withdrawers_list + ) { + if (typeof withdrawers_list == + "object") { + if ( + withdrawers_list + .length > + 0) { + withdrawers_list + .filter( + wd => + wd + .currency == + params + .currency + ).map( + function ( + withdrawer + ) { + if ( + withdrawer + .withdraw_amount == + params + .depositing_amount && + withdrawer + .currency == + params + .currency + ) { + withdrawer + .status = + 2; // A depositor has been asked to deposit money + withdrawer + .depositor_found_at = + + new Date(); + withdrawer + .depositor_flo_id = + receivedTradeInfo + .trader_flo_address; + updateinDB + ( + "withdraw_cash", + withdrawer, + withdrawer + .trader_flo_address + ); - readDB("localbitcoinUser", "00-01").then(function (su_data) { - if (typeof su_data == "object" && typeof su_data.myLocalFLOPublicKey == - "string" && - su_data.myLocalFLOPublicKey.length > 0 && - localbitcoinplusplus.master_configurations.supernodesPubKeys - .includes(su_data.myLocalFLOPublicKey)) { - let receivedTradeInfoHash = Crypto.SHA256(JSON.stringify(receivedTradeInfo)); + receivedTradeInfo + .status = + 2; // withdrawer found. Now deposit money to his account + updateinDB + ( + "deposit", + receivedTradeInfo, + receivedTradeInfo + .trader_flo_address + ); - receivedTradeInfo["depositDataHash"] = receivedTradeInfoHash; - receivedTradeInfo["order_validator_sign"] = RM_WALLET.sign( - receivedTradeInfoHash, localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY - ); - receivedTradeInfo["order_validator_public_key"] = su_data.myLocalFLOPublicKey; + let + withdrawer_bank_account = + withdrawer + .receivinAddress; - // YOU NEED TO DETERMINE A BANK ACCOUNT HERE IF NO ONE IS WITHDRAWING - try { - addDB("deposit", receivedTradeInfo); - readDBbyIndex("withdraw_cash", "status", 1).then( - function (withdrawers_list) { - if (typeof withdrawers_list == "object") { - if (withdrawers_list.length > 0) { - withdrawers_list.filter(wd=>wd.currency == params.currency).map( - function (withdrawer) { - if (withdrawer.withdraw_amount == params.depositing_amount - && withdrawer.currency == params.currency - ) { - withdrawer.status = 2; // A depositor has been asked to deposit money - withdrawer.depositor_found_at = + new Date(); - withdrawer.depositor_flo_id = receivedTradeInfo.trader_flo_address; - updateinDB("withdraw_cash", withdrawer, withdrawer.trader_flo_address); + let + deposit_response_object = { + error: false, + method: "deposit_asset_request_response", + msg: `Plese send the money to following bank address: "${withdrawer_bank_account}"`, + data: receivedTradeInfo, + withdrawer_data: withdrawer + }; + let + deposit_request_response = + RM_RPC + .send_rpc + .call( + this, + "deposit_asset_request_response", + deposit_response_object + ); - receivedTradeInfo.status = 2; // withdrawer found. Now deposit money to his account - updateinDB("deposit", receivedTradeInfo, receivedTradeInfo.trader_flo_address); - - let withdrawer_bank_account = withdrawer.receivinAddress; - - let deposit_response_object = { - error: false, - method: "deposit_asset_request_response", - msg: `Plese send the money to following bank address: "${withdrawer_bank_account}"`, - data: receivedTradeInfo, - withdrawer_data: withdrawer - }; - let deposit_request_response = + doSend + ( + deposit_request_response + ); + return true; + } else { + console + .warning( + "Deposit request failed: We could not find a withdrawer." + ); + } + } + ); + } else { + //No one is withdrawing so provide your bank details + let + deposit_response_object = { + error: false, + method: "deposit_asset_request_response", + msg: `Plese send the money to following bank address: "System determined bank".`, + data: receivedTradeInfo + }; + let + deposit_request_response = RM_RPC .send_rpc .call( @@ -35982,45 +37508,36 @@ exports.createContext = Script.createContext = function (context) { "deposit_asset_request_response", deposit_response_object ); - - doSend(deposit_request_response); + + receivedTradeInfo + .status = + 2; // withdrawer found. Now deposit money to his account + updateinDB + ( + "deposit", + receivedTradeInfo, + receivedTradeInfo + .trader_flo_address + ); + + doSend( + deposit_request_response + ); return true; - } else { - console.warning("Deposit request failed: We could not find a withdrawer."); } - }); - } else { - //No one is withdrawing so provide your bank details - let deposit_response_object = { - error: false, - method: "deposit_asset_request_response", - msg: `Plese send the money to following bank address: "System determined bank".`, - data: receivedTradeInfo - }; - let deposit_request_response = - RM_RPC.send_rpc - .call(this, - "deposit_asset_request_response", - deposit_response_object - ); - - receivedTradeInfo.status = 2; // withdrawer found. Now deposit money to his account - updateinDB("deposit", receivedTradeInfo, receivedTradeInfo.trader_flo_address); - - doSend(deposit_request_response); - return true; - } + } + }); + } catch (error) { + console.error( + "Deposit request failed: We could not find a withdrawer. Come again later." + ); + throw new Error(error); } - }); - } catch (error) { - console.error("Deposit request failed: We could not find a withdrawer. Come again later."); - throw new Error(error); - } + } + }); } }); - } - }); } else { console.log("deposit asset request error"); @@ -36033,54 +37550,82 @@ exports.createContext = Script.createContext = function (context) { if (is_valid_request !== true) return false; - if (typeof params.product !== "undefined" - && (localbitcoinplusplus.master_configurations.tradableAsset1.includes(params.product) - || localbitcoinplusplus.master_configurations.tradableAsset2.includes(params.currency)) && + if (typeof params.product !== "undefined" && + (localbitcoinplusplus.master_configurations.tradableAsset1.includes( + params.product) || + localbitcoinplusplus.master_configurations.tradableAsset2.includes( + params.currency)) && typeof params.withdrawing_amount !== "undefined" && - typeof localbitcoinplusplus.master_configurations.validTradingAmount !== 'undefined' && + typeof localbitcoinplusplus.master_configurations.validTradingAmount !== + 'undefined' && localbitcoinplusplus.master_configurations.validTradingAmount.includes( parseFloat(params.withdrawing_amount)) && typeof params.trader_flo_address == "string" && params.trader_flo_address .length > 0 && - typeof params.receivinAddress == "string" && params.receivinAddress.length > + typeof params.receivinAddress == "string" && params.receivinAddress + .length > 0 && typeof params.currency == "string" ) { - await RM_TRADE.resolve_current_crypto_price_in_fiat(params.product, params.currency); - let trade_margin = await RM_TRADE.getAssetTradeAndWithdrawLimit(params.trader_flo_address, params.product, params.currency); + await RM_TRADE.resolve_current_crypto_price_in_fiat(params.product, + params.currency); + let trade_margin = await RM_TRADE.getAssetTradeAndWithdrawLimit( + params.trader_flo_address, params.product, params.currency + ); - if (localbitcoinplusplus.master_configurations.tradableAsset1.includes(params.product)) { - let eqCrypto = RM_TRADE.calculateCryptoEquivalentOfCash(params.withdrawing_amount); - if (trade_margin.remaining_crypto_credit<0 && trade_margin.remaining_crypto_credit 0) { - let withdrawer_btc_balance = parseFloat(btc_balance_res.crypto_balance); - let withdrawing_btc_amount_in_cash = parseFloat(params.withdrawing_amount); - if(!localbitcoinplusplus.master_configurations.tradableAsset2.includes(params.currency)) { - throw new Error("Invalid or unsupported currency."); + let withdrawer_btc_balance = parseFloat( + btc_balance_res.crypto_balance); + let withdrawing_btc_amount_in_cash = + parseFloat(params.withdrawing_amount); + if (!localbitcoinplusplus.master_configurations + .tradableAsset2.includes(params.currency) + ) { + throw new Error( + "Invalid or unsupported currency." + ); } let eqBTC = RM_TRADE.calculateCryptoEquivalentOfCash( - withdrawing_btc_amount_in_cash, params.currency, params.product); + withdrawing_btc_amount_in_cash, + params.currency, params.product); eqBTC = parseFloat(eqBTC).toFixed(8); - let withdrawer_new_btc_balance = withdrawer_btc_balance - eqBTC; + let withdrawer_new_btc_balance = + withdrawer_btc_balance - eqBTC; if (withdrawer_new_btc_balance > 0 && withdrawer_btc_balance > 0 && withdrawing_btc_amount_in_cash > 0 && - eqBTC > 0 && eqBTC <= withdrawer_btc_balance) { + eqBTC > 0 && eqBTC <= + withdrawer_btc_balance) { // Now details of Bitcoins can be sent to withdrawer @@ -36093,70 +37638,159 @@ exports.createContext = Script.createContext = function (context) { let receiverBTCAddress = params.receivinAddress .trim(); - readAllDB("deposit").then(function (deposit_list) { - if (typeof deposit_list == "object" && - deposit_list.length > 0) { - deposit_list = deposit_list.filter( - deposits => deposits.status == 2 - && localbitcoinplusplus.master_configurations.tradableAsset1.includes(deposits.product) - && params.product==deposits.product); - for (const dl in deposit_list) { - if (deposit_list.hasOwnProperty(dl)) { - const deposit_dl = deposit_list[dl]; - sum_total_btc += parseFloat(deposit_dl.bitcoinToBePaid); - - if (eqBTC <= sum_total_btc) { - valid_utxo_list.push(deposit_dl); + readAllDB("deposit").then(function ( + deposit_list) { + if (typeof deposit_list == + "object" && + deposit_list.length > 0 + ) { + deposit_list = + deposit_list.filter( + deposits => + deposits.status == + 2 && + localbitcoinplusplus + .master_configurations + .tradableAsset1 + .includes( + deposits.product + ) && + params.product == + deposits.product + ); + for (const dl in + deposit_list) { + if (deposit_list.hasOwnProperty( + dl)) { + const deposit_dl = + deposit_list[ + dl]; + sum_total_btc += + parseFloat( + deposit_dl + .bitcoinToBePaid + ); + + if (eqBTC <= + sum_total_btc + ) { + valid_utxo_list + .push( + deposit_dl + ); break; } else { - valid_utxo_list.push(deposit_dl); + valid_utxo_list + .push( + deposit_dl + ); } } } - let valid_btc_list = valid_utxo_list.map(deposit_arr => { - deposit_arr.status = 3 // Deposited Bitcoin is under process - updateinDB("deposit", deposit_arr, deposit_arr.trader_flo_address); - - // save the address and id in a table - let withdraw_id = helper_functions.unique_id(); - const withdraw_btc_order_object = { - id: withdraw_id, - trader_flo_address: params.trader_flo_address, - utxo_addr: deposit_arr.btc_address, - receiverBTCAddress: params.receivinAddress, - receiverBTCEquivalentInCash: withdrawing_btc_amount_in_cash, - currency: params.currency, - product: params.product, - change_adress:deposit_arr.btc_address, - timestamp: + new Date() - } - addDB('withdraw_btc', withdraw_btc_order_object); - return {withdraw_id:withdraw_id, deposited_btc_address:deposit_arr.btc_address}; - }); - - // doSend btc_private_key_shamirs_id from system_btc_reserves_private_keys - valid_btc_list.map(vbl=>{ - readDBbyIndex('system_btc_reserves_private_keys', 'btc_address', vbl.deposited_btc_address).then(function(res) { - let retrieve_pvtkey_req_id = res[0].id; - res[0].btc_private_key_shamirs_id.map(bpks=>{ - let retrieve_pvtkey_req = RM_RPC - .send_rpc - .call(this, "send_back_shamirs_secret_btc_pvtkey", - { retrieve_pvtkey_req_id:retrieve_pvtkey_req_id, - chunk_val:bpks, - withdraw_id:vbl.withdraw_id - }); - doSend(retrieve_pvtkey_req); + let valid_btc_list = + valid_utxo_list.map( + deposit_arr => { + deposit_arr + .status = + 3 // Deposited Bitcoin is under process + updateinDB( + "deposit", + deposit_arr, + deposit_arr + .trader_flo_address + ); + + // save the address and id in a table + let + withdraw_id = + helper_functions + .unique_id(); + const + withdraw_btc_order_object = { + id: withdraw_id, + trader_flo_address: params + .trader_flo_address, + utxo_addr: deposit_arr + .btc_address, + receiverBTCAddress: params + .receivinAddress, + receiverBTCEquivalentInCash: withdrawing_btc_amount_in_cash, + currency: params + .currency, + product: params + .product, + change_adress: deposit_arr + .btc_address, + timestamp: + + + new Date() + } + addDB( + 'withdraw_btc', + withdraw_btc_order_object + ); + return { + withdraw_id: withdraw_id, + deposited_btc_address: deposit_arr + .btc_address + }; }); - }); + + // doSend btc_private_key_shamirs_id from system_btc_reserves_private_keys + valid_btc_list.map(vbl => { + readDBbyIndex + ( + 'system_btc_reserves_private_keys', + 'btc_address', + vbl + .deposited_btc_address + ).then( + function ( + res + ) { + let + retrieve_pvtkey_req_id = + res[ + 0 + ] + .id; + res + [ + 0 + ] + .btc_private_key_shamirs_id + .map( + bpks => { + let + retrieve_pvtkey_req = + RM_RPC + .send_rpc + .call( + this, + "send_back_shamirs_secret_btc_pvtkey", { + retrieve_pvtkey_req_id: retrieve_pvtkey_req_id, + chunk_val: bpks, + withdraw_id: vbl + .withdraw_id + } + ); + doSend + ( + retrieve_pvtkey_req + ); + } + ); + }); }); - + } }); } else { - console.error(`Withdrawal request failed: You are trying to withdraw more Bitcoins than you have.`); - + console.error( + `Withdrawal request failed: You are trying to withdraw more Bitcoins than you have.` + ); + // Return error to the requester return { error: true, @@ -36165,9 +37799,11 @@ exports.createContext = Script.createContext = function (context) { }; } } else { - console.error(`Withdrawal request failed: You don't seem to have any Bitcoin balance in the system yet. - Please buy some Bitcoins to withdraw.`); - + console.error( + `Withdrawal request failed: You don't seem to have any Bitcoin balance in the system yet. + Please buy some Bitcoins to withdraw.` + ); + // Return error to the requester return { error: true, @@ -36177,21 +37813,27 @@ exports.createContext = Script.createContext = function (context) { }; } }); - } else if (!localbitcoinplusplus.master_configurations.tradableAsset1.includes(params.product)) { + } else if (!localbitcoinplusplus.master_configurations.tradableAsset1 + .includes(params.product)) { // Check if there's no already a withdraw cash order of this user /*ONLY DELETE A WITHDRAW ORDER WHEN A DEPOSITOR HAS CONFIRMED DEPOSIT AND RECEIVER HAS CONFIRMED WITHDRAW*/ // Check how much Cash user can withdraw - const trader_cash_id = `${params.trader_flo_address}_${params.currency}`; + const trader_cash_id = + `${params.trader_flo_address}_${params.currency}`; readDB("cash_balances", trader_cash_id).then(function ( 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" && - typeof cash_balances_res.cash_balance == "number" && + typeof cash_balances_res.cash_balance == + "number" && cash_balances_res.cash_balance > 0) { - let withdrawer_cash_balance = parseFloat(cash_balances_res.cash_balance); - let withdrawing_cash_amount = parseFloat(params.withdrawing_amount); + let withdrawer_cash_balance = parseFloat( + cash_balances_res.cash_balance); + let withdrawing_cash_amount = parseFloat( + params.withdrawing_amount); let bank_details = params.receivinAddress.trim(); if (withdrawer_cash_balance > 0 && @@ -36208,59 +37850,73 @@ exports.createContext = Script.createContext = function (context) { status: 1 // withdraw request called } - readDB("localbitcoinUser", "00-01").then(function ( - su_data) { - if (typeof su_data == "object" && - typeof su_data.myLocalFLOPublicKey == - "string" && - su_data.myLocalFLOPublicKey.length > - 0 && localbitcoinplusplus.master_configurations - .supernodesPubKeys.includes( + readDB("localbitcoinUser", "00-01").then( + function ( + su_data) { + if (typeof su_data == + "object" && + typeof su_data.myLocalFLOPublicKey == + "string" && su_data.myLocalFLOPublicKey - )) { + .length > + 0 && + localbitcoinplusplus.master_configurations + .supernodesPubKeys.includes( + su_data.myLocalFLOPublicKey + )) { - let - withdraw_request_db_object_hash = - Crypto.SHA256(JSON.stringify( - withdraw_request_db_object - )); - withdraw_request_db_object["withdrawDataHash"] = - withdraw_request_db_object_hash; - withdraw_request_db_object[ - "order_validator_sign"] = - RM_WALLET - .sign( - withdraw_request_db_object_hash, - localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY - ); - withdraw_request_db_object[ - "order_validator_public_key" - ] = su_data.myLocalFLOPublicKey; - - try { - // add the request to supernode db - addDB("withdraw_cash", - withdraw_request_db_object - ); - // return back the response to client let - withdrawal_request_response = - RM_RPC.send_rpc - .call(this, - "withdrawal_request_response", + withdraw_request_db_object_hash = + Crypto.SHA256(JSON.stringify( + withdraw_request_db_object + )); + withdraw_request_db_object + ["withdrawDataHash"] = + withdraw_request_db_object_hash; + withdraw_request_db_object + [ + "order_validator_sign" + ] = + RM_WALLET + .sign( + withdraw_request_db_object_hash, + localbitcoinplusplus + .wallets.MY_SUPERNODE_PRIVATE_KEY + ); + withdraw_request_db_object + [ + "order_validator_public_key" + ] = su_data.myLocalFLOPublicKey; + + try { + // add the request to supernode db + addDB( + "withdraw_cash", withdraw_request_db_object ); - doSend(withdrawal_request_response); - return true; - } catch (error) { - console.log(error); + // return back the response to client + let + withdrawal_request_response = + RM_RPC.send_rpc + .call(this, + "withdrawal_request_response", + withdraw_request_db_object + ); + doSend( + withdrawal_request_response + ); + return true; + } catch (error) { + console.log(error); + } } - } - }); + }); } else { // Return error to the requester - console.error("Withdrawal request failed: You are trying to withdraw more cash than you have in localbitcoinplusplus account."); + console.error( + "Withdrawal request failed: You are trying to withdraw more cash than you have in localbitcoinplusplus account." + ); } } }); @@ -36273,107 +37929,251 @@ exports.createContext = Script.createContext = function (context) { case "retrieve_shamirs_secret_btc_pvtkey": RM_RPC.filter_legit_requests(function (is_valid_request) { - if (is_valid_request !== true) return false; + if (is_valid_request !== true) return false; - if (typeof params.btc_private_key_array !== "string" || typeof params.retrieve_pvtkey_req_id !== "string") return false; + if (typeof params.btc_private_key_array !== "string" || typeof params.retrieve_pvtkey_req_id !== + "string") return false; - let btc_private_key_str = params.btc_private_key_array; - let retrieve_pvtkey_req_id = params.retrieve_pvtkey_req_id; - let withdraw_id = params.withdraw_id; + let btc_private_key_str = params.btc_private_key_array; + let retrieve_pvtkey_req_id = params.retrieve_pvtkey_req_id; + let withdraw_id = params.withdraw_id; - try { - let btc_private_key_object = JSON.parse(btc_private_key_str); - let btc_pk_shares_array = btc_private_key_object.map(pkChunks=>{ - if(typeof pkChunks.private_key_chunk !== "undefined") return pkChunks.private_key_chunk.privateKeyChunks; - }).filter(val => val !== undefined); - console.log(btc_pk_shares_array); + try { + let btc_private_key_object = JSON.parse(btc_private_key_str); + let btc_pk_shares_array = btc_private_key_object.map(pkChunks => { + if (typeof pkChunks.private_key_chunk !== "undefined") + return pkChunks.private_key_chunk.privateKeyChunks; + }).filter(val => val !== undefined); + console.log(btc_pk_shares_array); - readDB('withdraw_btc', withdraw_id).then(function(withdraw_res) { - if (typeof withdraw_res == "object") { - readDB('system_btc_reserves_private_keys', retrieve_pvtkey_req_id).then(function(btc_reserves) { - if (typeof btc_reserves == "object") { - - // Ideally this line should never run. - if(btc_reserves.product !== withdraw_res.product) throw new Error("Mismatch of assets in withdrawal request."); - - let transaction_key = btc_reserves.supernode_transaction_key; - if (transaction_key.length>0) { - let btc_private_key = RM_WALLET.rebuild_private_key(btc_pk_shares_array, transaction_key); - console.log(btc_private_key); - - RM_TRADE.sendTransaction(withdraw_res.product, withdraw_res.utxo_addr, btc_private_key, withdraw_res.receiverBTCAddress, - withdraw_res.receiverBTCEquivalentInCash, withdraw_res.currency, withdraw_res.change_adress, async function(res) { - console.log(res); - if (typeof res == "string" && res.length>0) { - try { - let resp_obj = JSON.parse(res); - let resp_txid = resp_obj.txid.result || resp_obj.txid; - let msg = `Transaction Id for your withdrawn crypto asset: ${resp_txid}`; - writeToScreen(msg); - alert(msg); - return true; - } catch (error) { - console.warn(error); - } - } + readDB('withdraw_btc', withdraw_id).then(function (withdraw_res) { + if (typeof withdraw_res == "object") { + readDB('system_btc_reserves_private_keys', + retrieve_pvtkey_req_id).then(async function ( + btc_reserves) { + if (typeof btc_reserves == "object") { - // Check if there's BTC left in deposited BTC. If yes update its status to 2 else delete it + // Ideally this line should never run. + if (btc_reserves.product !== + withdraw_res.product) throw new Error( + "Mismatch of assets in withdrawal request." + ); - /*********************************************************************************************************************************** - *******************CHECK ACTUAL BTC BALANCE HERE THROUGH AN API AND UPDATE DEPOSIT TABLE**************************************************** - ************************************************************************************************************************************/ + await RM_TRADE.resolve_current_crypto_price_in_fiat( + withdraw_res.product, + withdraw_res.currency); + const EqCryptoWd = RM_TRADE.calculateCryptoEquivalentOfCash( + withdraw_res.receiverBTCEquivalentInCash, + withdraw_res.currency, + withdraw_res.product); + EqCryptoWd = parseFloat( + EqCryptoWd); - await RM_TRADE.resolve_current_crypto_price_in_fiat(withdraw_res.product, withdraw_res.currency); + let transaction_key = + btc_reserves.supernode_transaction_key; + if (transaction_key.length > 0) { + let btc_private_key = + RM_WALLET.rebuild_private_key( + btc_pk_shares_array, + transaction_key); + //console.log(btc_private_key); - readDBbyIndex('deposit', 'btc_address', withdraw_res.utxo_addr).then(function(deposit_arr_resp) { - if (typeof deposit_arr_resp=="object") { - deposit_arr_resp.map(deposit_arr=>{ - let eqBTC = RM_TRADE.calculateCryptoEquivalentOfCash(withdraw_res.receiverBTCEquivalentInCash, withdraw_res.currency, withdraw_res.product); - eqBTC = parseFloat(eqBTC); - deposit_arr.bitcoinToBePaid -= eqBTC; + RM_TRADE.sendTransaction( + withdraw_res.product, + withdraw_res.utxo_addr, + btc_private_key, + withdraw_res.receiverBTCAddress, + withdraw_res.receiverBTCEquivalentInCash, + withdraw_res.currency, + withdraw_res.change_adress, + async function (res) { + console.log( + res + ); + if (typeof res == + "string" && + res.length > + 0) { + try { + let + resp_obj = + JSON + .parse( + res + ); + let + resp_txid = + resp_obj + .txid + .result || + resp_obj + .txid; + let + msg = + `Transaction Id for your withdrawn crypto asset: ${resp_txid}`; - if (deposit_arr.bitcoinToBePaid > 0) { - // update deposits in db - deposit_arr.status = 2; // UTXO ready to be used again - updateinDB( - "deposit", - deposit_arr, - deposit_arr - .trader_flo_address - ); - - } else { - // delete entry in deposits in db - removeinDB + readDB ( - "deposit", - deposit_arr - .trader_flo_address + 'crypto_balances', + withdraw_res + .id + ) + .then( + res_bal => { + btc_eq_receiving_amount + = + parseFloat( + btc_eq_receiving_amount + ) + .toFixed( + 8 + ); + res_bal + .crypto_balance -= + EqCryptoWd; + updateinDB + ( + 'crypto_balances', + res_bal, + withdraw_res + .id + ) + .then( + res_obj => { + const + res_obj_str = + JSON + .stringify( + res_obj + ); + const + res_obj_hash = + Crypto + .SHA256( + res_obj_str + ); + const + res_obj_sign = + RM_WALLET + .sign( + res_obj_hash, + localbitcoinplusplus + .wallets + .MY_SUPERNODE_PRIVATE_KEY + ); + + const + updateUserCryptoBalanceObject = { + updatedBTCBalanceObject: res_bal, + updatedBTCBalanceObjectSign: res_obj_sign, + trader_flo_address: withdraw_res + .trader_flo_address + } + + const + updateUserCryptoBalanceRequestObject = + RM_RPC + .send_rpc( + "updateUserCryptoBalanceRequest", + updateUserCryptoBalanceObject + ); + doSend + ( + updateUserCryptoBalanceRequestObject + ); + + } + ) + + } + ); + } catch ( + error + ) { + console + .warn( + error ); } - }); - return true; - } - }); + } - }); + // Check if there's BTC left in deposited BTC. If yes update its status to 2 else delete it + + /*********************************************************************************************************************************** + *******************CHECK ACTUAL BTC BALANCE HERE THROUGH AN API AND UPDATE DEPOSIT TABLE**************************************************** + ************************************************************************************************************************************/ + + readDBbyIndex + ( + 'deposit', + 'btc_address', + withdraw_res + .utxo_addr + ).then( + function ( + deposit_arr_resp + ) { + if ( + typeof deposit_arr_resp == + "object" + ) { + deposit_arr_resp + .map( + deposit_arr => { + deposit_arr + .bitcoinToBePaid -= + EqCryptoWd; + + if ( + deposit_arr + .bitcoinToBePaid > + 0 + ) { + // update deposits in db + deposit_arr + .status = + 2; // UTXO ready to be used again + updateinDB + ( + "deposit", + deposit_arr, + deposit_arr + .trader_flo_address + ); + + } else { + // delete entry in deposits in db + removeinDB + ( + "deposit", + deposit_arr + .trader_flo_address + ); + } + } + ); + return true; + } + }); + + }); + } } - } - }); - } - }); + }); + } + }); - } catch (error) { - throw new Error(error); - } + } catch (error) { + throw new Error(error); + } - }); + }); break; case "superNodeSignedAddUserPublicData": - if (typeof params=="object" && typeof params.data=="object") { - if (typeof params.su_pubKey=="string" && localbitcoinplusplus - .master_configurations.supernodesPubKeys.includes(params.su_pubKey)) { + if (typeof params == "object" && typeof params.data == "object") { + if (typeof params.su_pubKey == "string" && localbitcoinplusplus + .master_configurations.supernodesPubKeys.includes(params.su_pubKey)) { let res_data_obj = { trader_flo_address: params.data.trader_flo_address, trader_flo_pubKey: params.data.trader_flo_pubKey, @@ -36383,7 +38183,7 @@ exports.createContext = Script.createContext = function (context) { let res_data_hash = Crypto.SHA256(JSON.stringify(res_data_obj)); let res_data_verification = RM_WALLET .verify(res_data_hash, params.sign, params.su_pubKey); - if ((res_data_verification==true) && res_data_hash==params.data_hash) { + if ((res_data_verification == true) && res_data_hash == params.data_hash) { addDB('userPublicData', params.data); return true; } @@ -36392,30 +38192,30 @@ exports.createContext = Script.createContext = function (context) { break; case "update_external_file_server_response": - if (typeof params=="object") { - if (params.filename=="UPDATE_ALL_FILES") { + if (typeof params == "object") { + if (params.filename == "UPDATE_ALL_FILES") { let file_details_str = JSON.stringify(params.file_updated); - if(RM_WALLET.verify(file_details_str, - params.server_sign, params.server_pubkey)) { - params.file_updated.map(new_file=>{ - updateinDB("external_files", new_file); - createScript(new_file.filename, new_file.content); - }); - return true; + if (RM_WALLET.verify(file_details_str, + params.server_sign, params.server_pubkey)) { + params.file_updated.map(new_file => { + updateinDB("external_files", new_file); + createScript(new_file.filename, new_file.content); + }); + return true; } } else { let file_details_string = JSON.stringify(params.file_updated); - if(RM_WALLET.verify(file_details_string, - params.server_sign, params.server_pubkey)) { - updateinDB("external_files", params.file_updated); - createScript(params.file_updated.filename, params.file_updated.content); - return true; + if (RM_WALLET.verify(file_details_string, + params.server_sign, params.server_pubkey)) { + updateinDB("external_files", params.file_updated); + createScript(params.file_updated.filename, params.file_updated.content); + return true; } } console.warn(`Failed to update external files from server.`); } - break; - + break; + default: alert("Unknown method called for execution."); break; @@ -36454,13 +38254,15 @@ exports.createContext = Script.createContext = function (context) { this.rpc_job = null; this.floAddress = null; this.user_flo_address = null; - this.sorted_trade_list = []; + this.sorted_trade_list = []; } Trade.prototype = { - getTrustLevel(){return this.level}, - + getTrustLevel() { + return this.level + }, + setTrustLevel(level) { if (typeof level === "number" && level === parseInt(level, 10) && level > 0 && level < 6) { this.level = level; @@ -36538,9 +38340,10 @@ exports.createContext = Script.createContext = function (context) { } } } - if (params.order_type != "buy" || !localbitcoinplusplus.master_configurations.tradableAsset1.includes(params.product) - || !localbitcoinplusplus.master_configurations.tradableAsset2.includes(params.currency) - || params.currency==params.product) { + if (params.order_type != "buy" || !localbitcoinplusplus.master_configurations.tradableAsset1.includes( + params.product) || + !localbitcoinplusplus.master_configurations.tradableAsset2.includes(params.currency) || + params.currency == params.product) { throw new Error("Invalid buy request."); } @@ -36558,7 +38361,8 @@ exports.createContext = Script.createContext = function (context) { throw new Error("Insufficient balance."); } // calculate equivalent BTC for x amount of Cash - let eqBTC = RM_TRADE.calculateCryptoEquivalentOfCash(buy_price_btc, params.currency, params.product); + let eqBTC = RM_TRADE.calculateCryptoEquivalentOfCash(buy_price_btc, params.currency, + params.product); eqBTC = parseFloat(eqBTC); if (typeof eqBTC == "number" && eqBTC > 0) { @@ -36566,8 +38370,10 @@ exports.createContext = Script.createContext = function (context) { // supernode data query readDB('localbitcoinUser', '00-01').then(function (user_data) { - if (typeof user_data == "object" && typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY == - "string" && localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY.length > + if (typeof user_data == "object" && typeof localbitcoinplusplus.wallets + .MY_SUPERNODE_PRIVATE_KEY == + "string" && localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY + .length > 0) { try { // Add buy oder @@ -36610,10 +38416,10 @@ exports.createContext = Script.createContext = function (context) { } } } - if (params.order_type != "sell" - || !localbitcoinplusplus.master_configurations.tradableAsset1.includes(params.product) - || !localbitcoinplusplus.master_configurations.tradableAsset2.includes(params.currency) - || params.currency==params.product) { + if (params.order_type != "sell" || + !localbitcoinplusplus.master_configurations.tradableAsset1.includes(params.product) || + !localbitcoinplusplus.master_configurations.tradableAsset2.includes(params.currency) || + params.currency == params.product) { throw new Error("Invalid sell request."); } @@ -36628,7 +38434,8 @@ exports.createContext = Script.createContext = function (context) { .length > 0 && res.crypto_balance > 0) { let seller_btc_balance = parseFloat(res.crypto_balance); let sell_price_in_inr = parseFloat(params.buy_price); - let eqBTC = RM_TRADE.calculateCryptoEquivalentOfCash(sell_price_in_inr, params.currency, params.product); + let eqBTC = RM_TRADE.calculateCryptoEquivalentOfCash(sell_price_in_inr, params.currency, + params.product); eqBTC = parseFloat(eqBTC); if (typeof eqBTC == "number" && eqBTC > 0) { @@ -36638,8 +38445,10 @@ exports.createContext = Script.createContext = function (context) { // supernode data query readDB('localbitcoinUser', '00-01').then(function (user_data) { - if (typeof user_data == "object" && typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY == - "string" && localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY.length > 0) { + if (typeof user_data == "object" && typeof localbitcoinplusplus.wallets + .MY_SUPERNODE_PRIVATE_KEY == + "string" && localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY + .length > 0) { //Add cash balance params['id'] = helper_functions.unique_id(); @@ -36670,9 +38479,9 @@ exports.createContext = Script.createContext = function (context) { }, depositAsset(assetType, amount, currency, userFLOaddress) { if (typeof localbitcoinplusplus.master_configurations.tradableAsset1 == 'undefined' || - typeof localbitcoinplusplus.master_configurations.tradableAsset2 == 'undefined' || - (!localbitcoinplusplus.master_configurations.tradableAsset1.includes(assetType) && - !localbitcoinplusplus.master_configurations.tradableAsset2.includes(assetType))) { + typeof localbitcoinplusplus.master_configurations.tradableAsset2 == 'undefined' || + (!localbitcoinplusplus.master_configurations.tradableAsset1.includes(assetType) && + !localbitcoinplusplus.master_configurations.tradableAsset2.includes(assetType))) { throw new Error("Invalid asset error"); } else if (parseFloat(amount) <= 0) { throw new Error("Invalid amount error."); @@ -36682,7 +38491,7 @@ exports.createContext = Script.createContext = function (context) { let deposit_request_object = { trader_flo_address: userFLOaddress, depositing_amount: amount, - currency:currency, + currency: currency, depositor_key_signature: null, depositor_public_key: null, operation_type: "deposit", @@ -36696,10 +38505,10 @@ exports.createContext = Script.createContext = function (context) { }, withdrawAsset(assetType, amount, receivinAddress, userFLOaddress, currency, callback) { if (typeof localbitcoinplusplus.master_configurations.tradableAsset1 == 'undefined' || - typeof localbitcoinplusplus.master_configurations.tradableAsset2 == 'undefined' || - (!localbitcoinplusplus.master_configurations.tradableAsset1.includes(assetType) && - !localbitcoinplusplus.master_configurations.tradableAsset2.includes(assetType) && - !localbitcoinplusplus.master_configurations.tradableAsset1.includes(currency))) { + typeof localbitcoinplusplus.master_configurations.tradableAsset2 == 'undefined' || + (!localbitcoinplusplus.master_configurations.tradableAsset1.includes(assetType) && + !localbitcoinplusplus.master_configurations.tradableAsset2.includes(assetType) && + !localbitcoinplusplus.master_configurations.tradableAsset1.includes(currency))) { throw new Error("Invalid asset error"); } else if (parseFloat(amount) <= 0) { throw new Error("Invalid amount error."); @@ -36725,13 +38534,13 @@ exports.createContext = Script.createContext = function (context) { "withdraw_request_method", withdraw_request_object); doSend(withdraw_request); }, - calculateCryptoEquivalentOfCash(price, currency="USD", crypto_code) { + calculateCryptoEquivalentOfCash(price, currency = "USD", crypto_code) { if (localbitcoinplusplus.master_configurations.validTradingAmount.includes(price)) { - if(!localbitcoinplusplus.master_configurations.tradableAsset1.includes(crypto_code)) return false; - if(!localbitcoinplusplus.master_configurations.tradableAsset2.includes(currency)) return false; + if (!localbitcoinplusplus.master_configurations.tradableAsset1.includes(crypto_code)) return false; + if (!localbitcoinplusplus.master_configurations.tradableAsset2.includes(currency)) return false; const RM_TRADE = new localbitcoinplusplus.trade; let current_crypto_price = RM_TRADE.get_current_crypto_price_in_fiat(crypto_code, currency); - if (typeof current_crypto_price=="object" && current_crypto_price.rate > 0) { + if (typeof current_crypto_price == "object" && current_crypto_price.rate > 0) { return parseFloat(price / current_crypto_price.rate).toFixed(8); } } @@ -36741,26 +38550,28 @@ exports.createContext = Script.createContext = function (context) { return localbitcoinplusplus.trade[`current_${crypto_code}_price_in_${currency_code}`]; }, async resolve_current_crypto_price_in_fiat(crypto_code, currency_code) { - let today = + new Date(); + let today = +new Date(); const RM_TRADE = new localbitcoinplusplus.trade; - let last_update_of_fiat_price_obj = RM_TRADE.get_current_crypto_price_in_fiat(crypto_code, currency_code); - if(typeof last_update_of_fiat_price_obj!=="object" - || (today-last_update_of_fiat_price_obj.timestamp>3600000)) { - last_update_of_fiat_price_obj = await RM_TRADE.set_current_crypto_price_in_fiat(crypto_code, currency_code); - return last_update_of_fiat_price_obj; + let last_update_of_fiat_price_obj = RM_TRADE.get_current_crypto_price_in_fiat(crypto_code, + currency_code); + if (typeof last_update_of_fiat_price_obj !== "object" || + (today - last_update_of_fiat_price_obj.timestamp > 3600000)) { + last_update_of_fiat_price_obj = await RM_TRADE.set_current_crypto_price_in_fiat(crypto_code, + currency_code); + return last_update_of_fiat_price_obj; } else { - return last_update_of_fiat_price_obj; + return last_update_of_fiat_price_obj; } }, async set_current_crypto_price_in_fiat(crypto_code, currency_code) { - if(!localbitcoinplusplus.master_configurations.tradableAsset1.includes(crypto_code) - || !localbitcoinplusplus.master_configurations.tradableAsset2.includes(currency_code)) return false; + if (!localbitcoinplusplus.master_configurations.tradableAsset1.includes(crypto_code) || + !localbitcoinplusplus.master_configurations.tradableAsset2.includes(currency_code)) return false; let new_price = 1000000; - - /************************** - Fetch latest rates here - ***************************/ - + + /************************** + Fetch latest rates here + ***************************/ + // if(crypto_code=="BTC" || crypto_code=="BTC_TEST") { // new_price = (currency_code=="USD") ? 3540 : 300000; // } else if(crypto_code=="FLO" || crypto_code=="FLO_TEST") { @@ -36768,44 +38579,49 @@ exports.createContext = Script.createContext = function (context) { // } Object.defineProperty(localbitcoinplusplus.trade, `current_${crypto_code}_price_in_${currency_code}`, { - value: {rate:new_price, - timestamp: + new Date()}, + value: { + rate: new_price, + timestamp: +new Date() + }, writable: true, configurable: false, enumerable: true - }); + }); return localbitcoinplusplus.trade[`current_${crypto_code}_price_in_${currency_code}`]; }, - sendTransaction(crypto_type, utxo_addr, utxo_addr_wif, receiver_address, receiving_amount, receiving_amount_currency=null, change_adress, callback) { + sendTransaction(crypto_type, utxo_addr, utxo_addr_wif, receiver_address, receiving_amount, + receiving_amount_currency = null, change_adress, callback) { let blockchain_explorer; - if (crypto_type=="BTC") { + if (crypto_type == "BTC") { blockchain_explorer = localbitcoinplusplus.server.btc_mainnet; - } else if(crypto_type=="BTC_TEST") { + } else if (crypto_type == "BTC_TEST") { blockchain_explorer = localbitcoinplusplus.server.btc_testnet; - } else if(crypto_type=="FLO") { + } else if (crypto_type == "FLO") { blockchain_explorer = localbitcoinplusplus.server.flo_mainnet; - } else if(crypto_type=="FLO_TEST") { + } else if (crypto_type == "FLO_TEST") { blockchain_explorer = localbitcoinplusplus.server.flo_testnet; } let url = `${blockchain_explorer}/api/addr/${utxo_addr}/utxo`; console.log(url); - - helper_functions.ajaxGet(url).then(utxo_list=>{ - + + helper_functions.ajaxGet(url).then(utxo_list => { + if (utxo_list.length > 0) { try { let btc_eq_receiving_amount = receiving_amount; - if (typeof receiving_amount_currency=="string") { - if (!localbitcoinplusplus.master_configurations.validTradingAmount.includes(receiving_amount)) { + if (typeof receiving_amount_currency == "string") { + if (!localbitcoinplusplus.master_configurations.validTradingAmount.includes( + receiving_amount)) { throw new Error('Invalid amount'); } const RM_TRADE = new localbitcoinplusplus.trade; - btc_eq_receiving_amount = RM_TRADE.calculateCryptoEquivalentOfCash(receiving_amount, receiving_amount_currency, crypto_type); - btc_eq_receiving_amount = parseFloat(btc_eq_receiving_amount).toFixed(8); + btc_eq_receiving_amount = RM_TRADE.calculateCryptoEquivalentOfCash( + receiving_amount, receiving_amount_currency, crypto_type); + btc_eq_receiving_amount = parseFloat(btc_eq_receiving_amount).toFixed(8); } - + let trx = bitjs[crypto_type].transaction(); let sum = 0; @@ -36813,7 +38629,7 @@ exports.createContext = Script.createContext = function (context) { if (utxo_list[key].confirmations > 0) { var obj = utxo_list[key]; sum += obj.satoshis; - + if (btc_eq_receiving_amount <= sum) { trx.addinput(obj.txid, obj.vout, obj.scriptPubKey); break; @@ -36826,15 +38642,15 @@ exports.createContext = Script.createContext = function (context) { sum = parseFloat(sum / 100000000).toFixed(8); let change_amount = sum - btc_eq_receiving_amount - 0.00006060; - + trx.addoutput(receiver_address, btc_eq_receiving_amount); trx.addoutput(change_adress, change_amount); var sendFloData = `localbitcoinpluslus tx: Send ${btc_eq_receiving_amount} satoshis to ${receiver_address}.`; //flochange adding place for flodata -- need a validation of 1024 chars - if(crypto_type=="FLO"||crypto_type=="FLO_TEST") { + if (crypto_type == "FLO" || crypto_type == "FLO_TEST") { trx.addflodata(sendFloData); // flochange .. create this function } - + try { console.log(trx); @@ -36862,17 +38678,19 @@ exports.createContext = Script.createContext = function (context) { throw new Error(error); } } - }).catch(e=>console.error(`No balance found in ${utxo_addr}: ${e}`)); + }).catch(e => console.error(`No balance found in ${utxo_addr}: ${e}`)); }, /*Finds the best buy sell id match for a trade*/ - createTradePipes(trading_currency="USD") { + createTradePipes(trading_currency = "USD") { try { readAllDB("sellOrders").then(function (sellOrdersList) { if (sellOrdersList.length > 0) { - sellOrdersList = sellOrdersList.filter(sellOrder=>sellOrder.currency==trading_currency); + sellOrdersList = sellOrdersList.filter(sellOrder => sellOrder.currency == + trading_currency); readAllDB("buyOrders").then(function (buyOrdersList) { if (buyOrdersList.length > 0) { - buyOrdersList = buyOrdersList.filter(buyOrder=>buyOrder.currency==trading_currency); + buyOrdersList = buyOrdersList.filter(buyOrder => buyOrder.currency == + trading_currency); let buy = []; let sell = []; let buysell = []; @@ -36881,22 +38699,34 @@ exports.createContext = Script.createContext = function (context) { let sellPipe = []; localbitcoinplusplus.master_configurations.validTradingAmount.map( li => { - buy[li] = buyOrdersList.filter(buyOrder=>buyOrder.buy_price==li); - sell[li] = sellOrdersList.filter(sellOrder=>sellOrder.buy_price==li); - buysell[li] = {"buy":buy[li], "sell":sell[li]}; - buysellArray[li] = Object.entries(buysell[li]).map(([key, value]) => ({key,value})); + buy[li] = buyOrdersList.filter(buyOrder => buyOrder + .buy_price == li); + sell[li] = sellOrdersList.filter(sellOrder => + sellOrder.buy_price == li); + buysell[li] = { + "buy": buy[li], + "sell": sell[li] + }; + buysellArray[li] = Object.entries(buysell[li]).map( + ([key, value]) => ({ + key, + value + })); buyPipe = buysellArray[li][0]; sellPipe = buysellArray[li][1]; - let n = buyPipe.value.length < sellPipe.value.length ? buyPipe.value.length : sellPipe.value.length; + let n = buyPipe.value.length < sellPipe.value.length ? + buyPipe.value.length : sellPipe.value.length; - if (buyPipe.value.length > 0 && sellPipe.value.length > 0) { + if (buyPipe.value.length > 0 && sellPipe.value.length > + 0) { const RM_TRADE = new localbitcoinplusplus.trade; const RM_RPC = new localbitcoinplusplus.rpc; for (let i = 0; i < n; i++) { RM_TRADE.launchTrade( buyPipe.value[i], sellPipe.value[i], function (supernode_res) { - if (typeof supernode_res == "object") { + if (typeof supernode_res == + "object") { let server_res = RM_RPC.send_rpc.call( this, @@ -36918,9 +38748,9 @@ exports.createContext = Script.createContext = function (context) { }, launchTrade(buyPipeObj, sellPipeObj, callback) { if (buyPipeObj.order_type == "buy" && sellPipeObj.order_type == "sell" && - buyPipeObj.buy_price == sellPipeObj.buy_price - && buyPipeObj.currency == sellPipeObj.currency - && buyPipeObj.product == sellPipeObj.product + buyPipeObj.buy_price == sellPipeObj.buy_price && + buyPipeObj.currency == sellPipeObj.currency && + buyPipeObj.product == sellPipeObj.product ) { const RM_TRADE = new localbitcoinplusplus.trade; const RM_WALLET = new localbitcoinplusplus.wallets; @@ -36935,7 +38765,8 @@ exports.createContext = Script.createContext = function (context) { throw new Error("Insufficient cash balance of buyer."); } // calculate equivalent BTC for x amount of Cash - let eqBTCBuyer = RM_TRADE.calculateCryptoEquivalentOfCash(buy_price_btc, buyPipeObj.currency, buyPipeObj.product); + let eqBTCBuyer = RM_TRADE.calculateCryptoEquivalentOfCash(buy_price_btc, + buyPipeObj.currency, buyPipeObj.product); if (!isNaN(eqBTCBuyer) && eqBTCBuyer != "" && eqBTCBuyer != undefined) { eqBTCBuyer = parseFloat(eqBTCBuyer); @@ -36950,7 +38781,8 @@ exports.createContext = Script.createContext = function (context) { .toFixed(8); let sell_price_in_inr = parseFloat(sellPipeObj.buy_price); let eqBTCSeller = RM_TRADE.calculateCryptoEquivalentOfCash( - sell_price_in_inr, buyPipeObj.currency, buyPipeObj.product); + sell_price_in_inr, buyPipeObj.currency, buyPipeObj.product + ); if (!isNaN(eqBTCSeller) && eqBTCSeller != "" && eqBTCSeller != undefined) { eqBTCSeller = parseFloat(eqBTCSeller); @@ -36960,7 +38792,8 @@ exports.createContext = Script.createContext = function (context) { // Increase buyer's crypto balance let buyerBTCResponseObject; - let buyer_btc_id = `${buyPipeObj.trader_flo_address}_${buyPipeObj.product}`; + let buyer_btc_id = + `${buyPipeObj.trader_flo_address}_${buyPipeObj.product}`; readDB("crypto_balances", buyPipeObj.trader_flo_address).then( function (buyPipeBTCRes) { if (typeof buyPipeBTCRes == "object" && typeof buyPipeBTCRes @@ -36992,7 +38825,8 @@ exports.createContext = Script.createContext = function (context) { // Increase seller's Cash balance let sellerCashResponseObject; - const seller_cash_id = `${sellPipeObj.trader_flo_address}_${buyPipeObj.currency}`; + const seller_cash_id = + `${sellPipeObj.trader_flo_address}_${buyPipeObj.currency}`; readDB("cash_balances", seller_cash_id).then( function (sellPipeCashRes) { if (typeof sellPipeCashRes == @@ -37003,153 +38837,167 @@ exports.createContext = Script.createContext = function (context) { sellPipeCashRes.cash_balance = parseFloat(sellPipeCashRes.cash_balance) + sell_price_in_inr; - sellerCashResponseObject = sellPipeCashRes; + sellerCashResponseObject = + sellPipeCashRes; } else { // User got cash for the first time - let seller_cash_id = `${sellPipeObj.trader_flo_address}_${buyPipeObj.currency}`; + let seller_cash_id = + `${sellPipeObj.trader_flo_address}_${buyPipeObj.currency}`; sellerCashResponseObject = { id: seller_cash_id, - trader_flo_address: sellPipeObj.trader_flo_address, + trader_flo_address: sellPipeObj + .trader_flo_address, currency: buyPipeObj.currency, cash_balance: sell_price_in_inr } } // Decrease seller BTC balance - let new_seller_btc_balance = seller_btc_balance - eqBTCSeller; - new_seller_btc_balance = parseFloat(new_seller_btc_balance).toFixed(8); + let new_seller_btc_balance = + seller_btc_balance - + eqBTCSeller; + new_seller_btc_balance = parseFloat( + new_seller_btc_balance).toFixed( + 8); let sellerBTCResponseObject = { id: `${sellPipeObj.trader_flo_address}_${sellPipeObj.product}`, - trader_flo_address: sellPipeObj.trader_flo_address, + trader_flo_address: sellPipeObj + .trader_flo_address, crypto_balance: new_seller_btc_balance, - crypto_currency: sellPipeObj.product + crypto_currency: sellPipeObj + .product } // supernode data query - readDB('localbitcoinUser', '00-01').then( - function (user_data) { - if (typeof user_data == - "object" && typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY == - "string" && - localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY - .length > 0) { - // Delete orders - try { - removeinDB( - "buyOrders", - buyPipeObj - .id); - removeinDB( - "sellOrders", - sellPipeObj - .id); - } catch (error) { - callback(false); - throw new Error(error); - } - - // Update balances - try { - updateinDB( - "cash_balances", - buyerCashResponseObject, - buyPipeObj - .trader_flo_address - ); - updateinDB( - "cash_balances", - sellerCashResponseObject, - sellPipeObj - .trader_flo_address - ); - updateinDB( - "crypto_balances", - buyerBTCResponseObject, - buyPipeObj - .trader_flo_address - ); - updateinDB( - "crypto_balances", - sellerBTCResponseObject, - sellPipeObj - .trader_flo_address - ); - } catch (error) { - callback(false); - throw new Error( - error); - } - - // Prepare response - let trade_infos = { - "buy_order_id": buyPipeObj - .id, - "sell_order_id": sellPipeObj - .id, - "buyer_flo_id": buyPipeObj - .trader_flo_address, - "seller_flo_id": sellPipeObj - .trader_flo_address - } - - let trade_infos_str = - JSON.stringify( - trade_infos - ); - let - buyerCashResponseObjectStr = - JSON.stringify( - buyerCashResponseObject - ); - let - sellerCashResponseObjectStr = - JSON.stringify( - sellerCashResponseObject - ); - let - buyerBTCResponseObjectStr = - JSON.stringify( - buyerBTCResponseObject - ); - let - sellerBTCResponseObjectStr = - JSON.stringify( - sellerBTCResponseObject - ); - - let res_str = - `${trade_infos_str}${buyerCashResponseObjectStr}${sellerCashResponseObjectStr}${buyerBTCResponseObjectStr}${sellerBTCResponseObjectStr}`; - - let hashed_data = - Crypto.SHA256( - res_str); - - // Signing of the data by Supernode - let signed_data = - RM_WALLET - .sign( - hashed_data, - localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY - ); - - let - response_for_client = { - "trade_infos": trade_infos, - "buyer_cash_data": buyerCashResponseObject, - "seller_cash_data": sellerCashResponseObject, - "buyer_btc_data": buyerBTCResponseObject, - "seller_btc_data": sellerBTCResponseObject, - "data_hash": hashed_data, - "supernode_sign": signed_data, - "supernodePubKey": user_data - .myLocalFLOPublicKey + readDB('localbitcoinUser', '00-01') + .then( + function (user_data) { + if (typeof user_data == + "object" && typeof localbitcoinplusplus + .wallets.MY_SUPERNODE_PRIVATE_KEY == + "string" && + localbitcoinplusplus + .wallets.MY_SUPERNODE_PRIVATE_KEY + .length > 0) { + // Delete orders + try { + removeinDB( + "buyOrders", + buyPipeObj + .id); + removeinDB( + "sellOrders", + sellPipeObj + .id); + } catch (error) { + callback(false); + throw new Error( + error); } - callback( - response_for_client - ); - return true; - } - }); + + // Update balances + try { + updateinDB( + "cash_balances", + buyerCashResponseObject, + buyPipeObj + .trader_flo_address + ); + updateinDB( + "cash_balances", + sellerCashResponseObject, + sellPipeObj + .trader_flo_address + ); + updateinDB( + "crypto_balances", + buyerBTCResponseObject, + buyPipeObj + .trader_flo_address + ); + updateinDB( + "crypto_balances", + sellerBTCResponseObject, + sellPipeObj + .trader_flo_address + ); + } catch (error) { + callback(false); + throw new Error( + error); + } + + // Prepare response + let trade_infos = { + "buy_order_id": buyPipeObj + .id, + "sell_order_id": sellPipeObj + .id, + "buyer_flo_id": buyPipeObj + .trader_flo_address, + "seller_flo_id": sellPipeObj + .trader_flo_address + } + + let trade_infos_str = + JSON.stringify( + trade_infos + ); + let + buyerCashResponseObjectStr = + JSON.stringify( + buyerCashResponseObject + ); + let + sellerCashResponseObjectStr = + JSON.stringify( + sellerCashResponseObject + ); + let + buyerBTCResponseObjectStr = + JSON.stringify( + buyerBTCResponseObject + ); + let + sellerBTCResponseObjectStr = + JSON.stringify( + sellerBTCResponseObject + ); + + let res_str = + `${trade_infos_str}${buyerCashResponseObjectStr}${sellerCashResponseObjectStr}${buyerBTCResponseObjectStr}${sellerBTCResponseObjectStr}`; + + let hashed_data = + Crypto.SHA256( + res_str); + + // Signing of the data by Supernode + let signed_data = + RM_WALLET + .sign( + hashed_data, + localbitcoinplusplus + .wallets.MY_SUPERNODE_PRIVATE_KEY + ); + + let + response_for_client = { + "trade_infos": trade_infos, + "buyer_cash_data": buyerCashResponseObject, + "seller_cash_data": sellerCashResponseObject, + "buyer_btc_data": buyerBTCResponseObject, + "seller_btc_data": sellerBTCResponseObject, + "data_hash": hashed_data, + "supernode_sign": signed_data, + "supernodePubKey": user_data + .myLocalFLOPublicKey + } + callback( + response_for_client + ); + return true; + } + }); }); }); } @@ -37159,21 +39007,21 @@ exports.createContext = Script.createContext = function (context) { }); callback(false); } - }, + }, cancelTrade(trade_id, trader_flo_address, trade_type) { - if(typeof trade_id !=="string") { + if (typeof trade_id !== "string") { alert("Failed to cancel the trade."); return false; } const RM_WALLET = new localbitcoinplusplus.wallets; const RM_RPC = new localbitcoinplusplus.rpc; - + const signed_trade_id = RM_WALLET.sign(trade_id, localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY); const cancel_trade_request_object = { job: `cancel_trade_request`, trade_id: trade_id, signed_trade_id: signed_trade_id, - trader_flo_address:trader_flo_address, + trader_flo_address: trader_flo_address, trade_type: trade_type } @@ -37182,21 +39030,28 @@ exports.createContext = Script.createContext = function (context) { doSend(cancel_trade_request); }, getAssetTradeAndWithdrawLimit(flo_id, crypto, fiat) { + + const RM_TRADE = new localbitcoinplusplus.trade; + let user_crypto_id = `${flo_id}_${crypto}`; let user_fiat_id = `${flo_id}_${fiat}`; - + const user_balance_crypto_promise = readDB("crypto_balances", user_crypto_id); const user_balance_fiat_promise = readDB("cash_balances", user_fiat_id); - const user_sell_orders_promise = readDBbyIndex("sellOrders", "trader_flo_address", flo_id) - .then((res)=>res.filter(resp=>resp.currency==fiat && resp.product==crypto)); + const user_sell_orders_promise = readDBbyIndex("sellOrders", "trader_flo_address", flo_id) + .then((res) => res.filter(resp => resp.currency == fiat && resp.product == crypto)); const user_buy_orders_promise = readDBbyIndex("buyOrders", "trader_flo_address", flo_id) - .then((res)=>res.filter(resp=>resp.currency==fiat && resp.product==crypto)); - const user_fiat_withdraw_request_promise = readDBbyIndex("withdraw_cash", "trader_flo_address", flo_id); - const user_crypto_withdraw_request_promise = readDBbyIndex("withdraw_btc", "trader_flo_address", flo_id); - - return Promise.all([user_balance_crypto_promise, user_balance_fiat_promise, user_sell_orders_promise, user_buy_orders_promise, - user_fiat_withdraw_request_promise, user_crypto_withdraw_request_promise]).then(resp=>{ - + .then((res) => res.filter(resp => resp.currency == fiat && resp.product == crypto)); + const user_fiat_withdraw_request_promise = readDBbyIndex("withdraw_cash", "trader_flo_address", + flo_id); + const user_crypto_withdraw_request_promise = readDBbyIndex("withdraw_btc", "trader_flo_address", + flo_id); + + return Promise.all([user_balance_crypto_promise, user_balance_fiat_promise, + user_sell_orders_promise, user_buy_orders_promise, + user_fiat_withdraw_request_promise, user_crypto_withdraw_request_promise + ]).then(resp => { + let user_balance_crypto = resp[0]; let user_balance_fiat = resp[1]; let user_sell_orders = resp[2]; @@ -37206,40 +39061,45 @@ exports.createContext = Script.createContext = function (context) { let remaining_crypto_credit = 0; let remaining_fiat_credit = 0; - let user_crypto_balance_value = (typeof user_balance_crypto=="undefined") ? 0 : user_balance_crypto.crypto_balance; - let user_cash_balance_value = (typeof user_balance_fiat=="undefined") ? 0 : user_balance_fiat.cash_balance; + let user_crypto_balance_value = (typeof user_balance_crypto == "undefined") ? 0 : + user_balance_crypto.crypto_balance; + let user_cash_balance_value = (typeof user_balance_fiat == "undefined") ? 0 : + user_balance_fiat.cash_balance; let sell_order_crypto_equivalent = 0; - user_sell_orders.map(sell_orders=>{ + user_sell_orders.map(sell_orders => { sell_order_crypto_eq = RM_TRADE.calculateCryptoEquivalentOfCash( sell_orders.sell_price, sell_orders.currency, sell_orders.product); sell_order_crypto_equivalent += Number(sell_order_crypto_eq); }); let withdraw_crypto_equivalent = 0; - user_crypto_withdraw_request.map(req=>{ - withdraw_crypto_eq = RM_TRADE.calculateCryptoEquivalentOfCash(req.receiverBTCEquivalentInCash, req.currency, req.product); + user_crypto_withdraw_request.map(req => { + withdraw_crypto_eq = RM_TRADE.calculateCryptoEquivalentOfCash(req.receiverBTCEquivalentInCash, + req.currency, req.product); withdraw_crypto_equivalent += Number(withdraw_crypto_eq); }); - - remaining_crypto_credit = user_crypto_balance_value - sell_order_crypto_equivalent - withdraw_crypto_equivalent; + + remaining_crypto_credit = user_crypto_balance_value - sell_order_crypto_equivalent - + withdraw_crypto_equivalent; let total_buy_orders_cash = 0; - user_buy_orders.map(buy_order=>total_buy_orders_cash += buy_order.buy_price); + user_buy_orders.map(buy_order => total_buy_orders_cash += buy_order.buy_price); let withdraw_cash_equivalent = 0; - user_fiat_withdraw_request.map(req=>{ + user_fiat_withdraw_request.map(req => { withdraw_cash_equivalent += req.withdraw_amount; }); - remaining_fiat_credit = user_cash_balance_value - total_buy_orders_cash - withdraw_cash_equivalent; + remaining_fiat_credit = user_cash_balance_value - total_buy_orders_cash - + withdraw_cash_equivalent; return { remaining_crypto_credit: remaining_crypto_credit, - remaining_fiat_credit : remaining_fiat_credit - }; + remaining_fiat_credit: remaining_fiat_credit + }; - }).catch(e=>console.warn(e)); + }).catch(e => console.warn(e)); }, } @@ -37264,20 +39124,20 @@ exports.createContext = Script.createContext = function (context) { //AJAX Post ajaxPost: function (url = ``, data = {}) { return fetch(url, { - method: "POST", // *GET, POST, PUT, DELETE, etc. - mode: "cors", // no-cors, cors, *same-origin - cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached - credentials: "same-origin", // include, *same-origin, omit - headers: { - "Content-Type": "application/json", - // "Content-Type": "application/x-www-form-urlencoded", - }, - redirect: "follow", // manual, *follow, error - referrer: "no-referrer", // no-referrer, *client - body: JSON.stringify(data), // body data type must match "Content-Type" header - }) - .then(response => response.json()); // parses response to JSON - }, + method: "POST", // *GET, POST, PUT, DELETE, etc. + mode: "cors", // no-cors, cors, *same-origin + cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached + credentials: "same-origin", // include, *same-origin, omit + headers: { + "Content-Type": "application/json", + // "Content-Type": "application/x-www-form-urlencoded", + }, + redirect: "follow", // manual, *follow, error + referrer: "no-referrer", // no-referrer, *client + body: JSON.stringify(data), // body data type must match "Content-Type" header + }) + .then(response => response.json()); // parses response to JSON + }, // Create unique id unique_id: function () { @@ -37295,10 +39155,10 @@ exports.createContext = Script.createContext = function (context) { callbacks = {}; /** - * Constructs a new JSON-RPC Request - * @param method A String containing the name of the method to be invoked. - * @param params (optional) A Structured value that holds the parameter values to be used during the invocation of the method. - */ + * Constructs a new JSON-RPC Request + * @param method A String containing the name of the method to be invoked. + * @param params (optional) A Structured value that holds the parameter values to be used during the invocation of the method. + */ JSON_RPC.Request = function (method, params) { this.jsonrpc = "2.0"; this.method = method; @@ -37338,9 +39198,9 @@ exports.createContext = Script.createContext = function (context) { }); /** - * Returns a String representation of a JSON-RPC Request - * @returns A JSON String - */ + * Returns a String representation of a JSON-RPC Request + * @returns A JSON String + */ JSON_RPC.Request.prototype.toString = function () { var rpc = { jsonrpc: this.jsonrpc, @@ -37356,10 +39216,10 @@ exports.createContext = Script.createContext = function (context) { }; /** - * Constructs a new JSON-RPC Notification - * @param method A String containing the name of the method to be invoked. - * @param params (optional) A Structured value that holds the parameter values to be used during the invocation of the method. - */ + * Constructs a new JSON-RPC Notification + * @param method A String containing the name of the method to be invoked. + * @param params (optional) A Structured value that holds the parameter values to be used during the invocation of the method. + */ JSON_RPC.Notification = function (method, params) { this.jsonrpc = "2.0"; this.method = method; @@ -37369,9 +39229,9 @@ exports.createContext = Script.createContext = function (context) { }; /** - * Returns a String representation of a JSON-RPC Notification - * @returns A JSON String - */ + * Returns a String representation of a JSON-RPC Notification + * @returns A JSON String + */ JSON_RPC.Notification.prototype.toString = function () { var rpc = { jsonrpc: this.jsonrpc, @@ -37383,11 +39243,11 @@ exports.createContext = Script.createContext = function (context) { }; /** - * Constructs a new JSON-RPC Errror object - * @params code A Number that indicates the error type that occurred. -32768 to -32000 are reserved. - * @param message (optional) A String providing a short description of the error. - * @param data (optional) A Primitive or Structured value that contains additional information about the error. - */ + * Constructs a new JSON-RPC Errror object + * @params code A Number that indicates the error type that occurred. -32768 to -32000 are reserved. + * @param message (optional) A String providing a short description of the error. + * @param data (optional) A Primitive or Structured value that contains additional information about the error. + */ JSON_RPC.Error = function (code, message, data) { this.code = code; if (typeof message == "string") this.message = message; @@ -37403,9 +39263,9 @@ exports.createContext = Script.createContext = function (context) { JSON_RPC.INTERNAL_ERROR = new JSON_RPC.Error(-32603, "Internal JSON-RPC error."); /** - * Parses a JSON-RPC string and converts to a JSON-RPC object or an Array of such strings. - * @params rpc A String or Array to parse to a JSON-RPC object. - */ + * Parses a JSON-RPC string and converts to a JSON-RPC object or an Array of such strings. + * @params rpc A String or Array to parse to a JSON-RPC object. + */ JSON_RPC.parse = function (rpc) { // batch? if (rpc.constructor === Array) { @@ -37459,9 +39319,9 @@ exports.createContext = Script.createContext = function (context) { /* JSON RPC Library Ends */ /******************************************************* - Custom Localbitcoin++ JSON-RPC code starts here - *********************************************************/ - + Custom Localbitcoin++ JSON-RPC code starts here + *********************************************************/ + /* Websocket Code Starts here */ var output; @@ -37469,65 +39329,74 @@ exports.createContext = Script.createContext = function (context) { function init() { output = document.getElementById("output_div"); const RM_WALLET = new localbitcoinplusplus.wallets; - return new Promise(resolve=>{ + return new Promise(resolve => { readDB("localbitcoinUser", "00-01").then(async function (idbData) { if (typeof idbData.myLocalFLOPublicKey == "undefined" || idbData.myLocalFLOPublicKey .trim() == '') { - let user_pvt_key = prompt("Please Enter a valid FLO private key if you have any. Else leave blank."); - - if (user_pvt_key.trim() == "" || user_pvt_key.length<1) user_pvt_key = null; - + let user_pvt_key = prompt( + "Please Enter a valid FLO private key if you have any. Else leave blank." + ); + + if (user_pvt_key.trim() == "" || user_pvt_key.length < 1) user_pvt_key = + null; + let newKeys = RM_WALLET.generateFloKeys(user_pvt_key); - if (typeof newKeys == 'object' && newKeys.privateKeyWIF.length > 0 - && newKeys.address.length > 0) { + if (typeof newKeys == 'object' && newKeys.privateKeyWIF.length > 0 && + newKeys.address.length > 0) { localbitcoinplusplusObj.myLocalFLOAddress = newKeys.address; localbitcoinplusplusObj.myLocalFLOPublicKey = newKeys.pubKeyHex; - + updateinDB("localbitcoinUser", localbitcoinplusplusObj, "00-01"); - - wsUri = await localbitcoinplusplus.kademlia.getSupernodeSeed(localbitcoinplusplusObj.myLocalFLOAddress, + + wsUri = await localbitcoinplusplus.kademlia.getSupernodeSeed( + localbitcoinplusplusObj.myLocalFLOAddress, localbitcoinplusplusObj.myLocalFLOPublicKey); - + await startWebSocket(wsUri); // Add new user node in Kademlia addDB('kBucketStore', { id: localbitcoinplusplusObj.myLocalFLOAddress, - data: {id: localbitcoinplusplusObj.myLocalFLOAddress, vectorClock: 0}, - }).then(dbObj=>{ - localbitcoinplusplus.kademlia.addNewUserNodeInKbucket("FLO_TEST", + data: { + id: localbitcoinplusplusObj.myLocalFLOAddress, + vectorClock: 0 + }, + }).then(dbObj => { + localbitcoinplusplus.kademlia.addNewUserNodeInKbucket( + "FLO_TEST", dbObj.id, dbObj.data); let addNewKNode = localbitcoinplusplus.rpc.prototype .send_rpc - .call(this, "addNewKbucketNode", - {newKbucketNode:dbObj}); + .call(this, "addNewKbucketNode", { + newKbucketNode: dbObj + }); console.log(addNewKNode); doSend(addNewKNode); }); - + RM_WALLET.distributeShamirsSecretShares(newKeys.privateKeyWIF) - .then(()=>privateKeyBuilder()); + .then(() => privateKeyBuilder()); resolve(true); return; - + } else { throw new Error("Failed to generate new FLO keys. Please retry."); } } wsUri = await localbitcoinplusplus.kademlia.getSupernodeSeed(idbData.myLocalFLOAddress, - idbData.myLocalFLOPublicKey); - + idbData.myLocalFLOPublicKey); + resolve(startWebSocket(wsUri)); }); }); } - + function startWebSocket(wsUri) { - return new Promise((resolve, reject)=>{ + return new Promise((resolve, reject) => { websocket = new WebSocket(wsUri); websocket.onopen = function (evt) { resolve(onOpen(evt)) @@ -37561,35 +39430,36 @@ exports.createContext = Script.createContext = function (context) { var res = response.substr(res_pos); try { var res_obj = JSON.parse(res); - + if (typeof res_obj.method !== undefined) { let response_from_sever; - + const RM_WALLET = new localbitcoinplusplus.wallets; const RM_TRADE = new localbitcoinplusplus.trade; const RM_RPC = new localbitcoinplusplus.rpc; switch (res_obj.method) { case "supernode_message": - if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object") { - let received_resp = res_obj.params[0]; - try { - if (received_resp.trader_flo_id.length>0 && received_resp.server_msg.length>0) { - readDB("localbitcoinUser", "00-01").then(function(res) { - if (typeof res=="object" && res.myLocalFLOAddress.length>0) { - if (res.myLocalFLOAddress===received_resp.trader_flo_id) { - writeToScreen(received_resp.server_msg); - alert(received_resp.server_msg); - return false; + if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object") { + let received_resp = res_obj.params[0]; + try { + if (received_resp.trader_flo_id.length > 0 && received_resp.server_msg.length > + 0) { + readDB("localbitcoinUser", "00-01").then(function (res) { + if (typeof res == "object" && res.myLocalFLOAddress.length > 0) { + if (res.myLocalFLOAddress === received_resp.trader_flo_id) { + writeToScreen(received_resp.server_msg); + alert(received_resp.server_msg); + return false; + } } - } - }); + }); + } + } catch (error) { + throw new Error(error); } - } catch (error) { - throw new Error(error); } - } - break; + break; case "trade_buy": response_from_sever = RM_RPC.receive_rpc_response.call(this, JSON.stringify(res_obj)); @@ -37606,7 +39476,7 @@ exports.createContext = Script.createContext = function (context) { buyOrders_data.supernodePubKey); if (isDataSignedBySuperNode === true) { // Add buy order - addDB("buyOrders", buyOrders_data).then(()=>{ + addDB("buyOrders", buyOrders_data).then(() => { showMessage(`Your buy order is placed successfully.`); }); } @@ -37629,7 +39499,7 @@ exports.createContext = Script.createContext = function (context) { sellOrders_data.supernodePubKey); if (isDataSignedBySuperNode === true) { // Add buy order - addDB("sellOrders", sellOrders_data).then(()=>{ + addDB("sellOrders", sellOrders_data).then(() => { showMessage(`Your sell order is placed successfully.`); });; } @@ -37642,48 +39512,54 @@ exports.createContext = Script.createContext = function (context) { break; case "server_sync_response": if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object") { - let su_db_data = res_obj.params[0]; - if (typeof localbitcoinplusplus.wallets.my_local_flo_address!=="string" - || su_db_data.trader_flo_address !== localbitcoinplusplus.wallets.my_local_flo_address) return false; - - (async function() { - for (let tableStoreName in su_db_data) { - // skip loop if the property is from prototype - if (tableStoreName=='trader_flo_address' || !su_db_data.hasOwnProperty(tableStoreName)) continue; + let su_db_data = res_obj.params[0]; + if (typeof localbitcoinplusplus.wallets.my_local_flo_address !== "string" || + su_db_data.trader_flo_address !== localbitcoinplusplus.wallets.my_local_flo_address + ) return false; - try { - let obj = su_db_data[tableStoreName]; - if (["crypto_balances", "cash_balances", "userPublicData"].includes(tableStoreName)) { - if (obj.length>0) { - for (var prop in obj) { - if(!obj.hasOwnProperty(prop)) continue; - await updateinDB(tableStoreName, obj[prop], obj[prop].trader_flo_address); - } + (async function () { + for (let tableStoreName in su_db_data) { + // skip loop if the property is from prototype + if (tableStoreName == 'trader_flo_address' || !su_db_data.hasOwnProperty( + tableStoreName)) continue; + + try { + let obj = su_db_data[tableStoreName]; + if (["crypto_balances", "cash_balances", "userPublicData"].includes( + tableStoreName)) { + if (obj.length > 0) { + for (var prop in obj) { + if (!obj.hasOwnProperty(prop)) continue; + await updateinDB(tableStoreName, obj[prop], obj[ + prop].trader_flo_address); } - } else { - let resdbdata = await removeAllinDB(tableStoreName); - if (resdbdata!==false) { - if (obj.length>0) { - for (var prop in obj) { - if(!obj.hasOwnProperty(prop)) continue; - await addDB(resdbdata, obj[prop]); - } + } + } else { + let resdbdata = await removeAllinDB(tableStoreName); + if (resdbdata !== false) { + if (obj.length > 0) { + for (var prop in obj) { + if (!obj.hasOwnProperty(prop)) continue; + await addDB(resdbdata, obj[prop]); } } } - - } catch (error) { - console.log(error); } - } - })() - // Pass data to build_deposit_withdraw_table function - try { - localbitcoinplusplus.actions.build_deposit_withdraw_table(su_db_data.withdraw_cash); - } catch (error) { - console.error(error); + } catch (error) { + console.log(error); + } } + })(); + + // Pass data to build_deposit_withdraw_table function + try { + console.log(su_db_data.withdraw_cash); + + localbitcoinplusplus.actions.build_deposit_withdraw_table(su_db_data.withdraw_cash); + } catch (error) { + console.error(error); + } } break; @@ -37698,7 +39574,7 @@ exports.createContext = Script.createContext = function (context) { .verify(resp.data.depositDataHash, resp.data.order_validator_sign, resp.data.order_validator_public_key) ) { addDB('deposit', resp.data); - if (typeof resp.withdrawer_data=="object") { + if (typeof resp.withdrawer_data == "object") { updateinDB("withdraw_cash", resp.withdrawer_data, resp.withdrawer_data.trader_flo_address); } readDB("localbitcoinUser", "00-01").then(function (user) { @@ -37706,8 +39582,7 @@ exports.createContext = Script.createContext = function (context) { let counterTraderAccountAddress = `

    Please pay the amount to following address:

    ${resp.msg}

    `; - let asset_boxx = document.getElementById("asset_box"); - asset_boxx.insertAdjacentHTML('beforeend', counterTraderAccountAddress); + alert(counterTraderAccountAddress); } }); } @@ -37723,7 +39598,7 @@ exports.createContext = Script.createContext = function (context) { if (RM_WALLET .verify(res_obj.params[0].withdrawDataHash, res_obj.params[0].order_validator_sign, res_obj.params[0].order_validator_public_key)) { - addDB('withdraw_cash', res_obj.params[0]).then(()=>{ + addDB('withdraw_cash', res_obj.params[0]).then(() => { showMessage(`Your cash withdrawal request is placed successfully.`); }); } @@ -37732,18 +39607,23 @@ exports.createContext = Script.createContext = function (context) { case "cancel_trade": if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object") { let cancel_request = res_obj.params[0]; - if (cancel_request.job=="cancel_trade_request") { - readDB("userPublicData", cancel_request.trader_flo_address).then((trader_data)=>{ - if(typeof trader_data.trader_flo_address !=="string" || typeof trader_data.trader_flo_pubKey !=="string") { + if (cancel_request.job == "cancel_trade_request") { + readDB("userPublicData", cancel_request.trader_flo_address).then((trader_data) => { + if (typeof trader_data.trader_flo_address !== "string" || typeof trader_data + .trader_flo_pubKey !== "string") { throw new Error("Unverified user"); } - tradeDB = cancel_request.trade_type == "buy" ? "buyOrders":"sellOrders"; - if(RM_WALLET - .verify(cancel_request.trade_id, cancel_request.signed_trade_id, trader_data.trader_flo_pubKey)) { + tradeDB = cancel_request.trade_type == "buy" ? "buyOrders" : + "sellOrders"; + if (RM_WALLET + .verify(cancel_request.trade_id, cancel_request.signed_trade_id, + trader_data.trader_flo_pubKey)) { removeinDB(tradeDB, cancel_request.trade_id) - .then((id)=>showMessage(`Trade Id ${id} deleted.`)); + .then((id) => showMessage(`Trade Id ${id} deleted.`)); } else { - showMessage(`Failed to verify trade for trade id ${cancel_request.trade_id}`); + showMessage( + `Failed to verify trade for trade id ${cancel_request.trade_id}` + ); } }) } else { @@ -37803,189 +39683,256 @@ exports.createContext = Script.createContext = function (context) { break; case "send_back_shamirs_secret_supernode_pvtkey": if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object") { - readDB("supernode_private_key_chunks", res_obj.params[0].chunk_val).then(function(res) { + readDB("supernode_private_key_chunks", res_obj.params[0].chunk_val).then(function ( + res) { let send_pvtkey_req = RM_RPC .send_rpc - .call(this, "retrieve_shamirs_secret_supernode_pvtkey", - {private_key_chunk:res}); + .call(this, "retrieve_shamirs_secret_supernode_pvtkey", { + private_key_chunk: res + }); doSend(send_pvtkey_req); }); } break; case "retrieve_shamirs_secret_supernode_pvtkey": - - if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object" - && typeof res_obj.params[0].private_key_chunk=="object" - && typeof localbitcoinplusplus.wallets.supernode_transaction_key == "object") { - let share = res_obj.params[0].private_key_chunk.privateKeyChunks; - if (typeof share !== "undefined" && !MY_PRIVATE_KEY_SHAMIRS_SHARES.includes(share)) { - MY_PRIVATE_KEY_SHAMIRS_SHARES.push(share); - } - if (MY_PRIVATE_KEY_SHAMIRS_SHARES.length==5) { - RM_WALLET.rebuild_my_private_key(localbitcoinplusplus.wallets.supernode_transaction_key); - return; - } + + if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object" && + typeof res_obj.params[0].private_key_chunk == "object" && + typeof localbitcoinplusplus.wallets.supernode_transaction_key == "object") { + let share = res_obj.params[0].private_key_chunk.privateKeyChunks; + if (typeof share !== "undefined" && !MY_PRIVATE_KEY_SHAMIRS_SHARES.includes(share)) { + MY_PRIVATE_KEY_SHAMIRS_SHARES.push(share); + } + if (MY_PRIVATE_KEY_SHAMIRS_SHARES.length == 5) { + RM_WALLET.rebuild_my_private_key(localbitcoinplusplus.wallets.supernode_transaction_key); + return; + } } break; case "send_back_shamirs_secret_btc_pvtkey": if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object") { - readDB("supernode_private_key_chunks", res_obj.params[0].chunk_val).then(function(res) { + readDB("supernode_private_key_chunks", res_obj.params[0].chunk_val).then(function ( + res) { let send_pvtkey_req = RM_RPC .send_rpc - .call(this, "retrieve_shamirs_secret_btc_pvtkey", - { - retrieve_pvtkey_req_id:res_obj.params[0].retrieve_pvtkey_req_id, - private_key_chunk:res, - withdraw_id:res_obj.params[0].withdraw_id + .call(this, "retrieve_shamirs_secret_btc_pvtkey", { + retrieve_pvtkey_req_id: res_obj.params[0].retrieve_pvtkey_req_id, + private_key_chunk: res, + withdraw_id: res_obj.params[0].withdraw_id }); doSend(send_pvtkey_req); }); } break; case "retrieve_shamirs_secret_btc_pvtkey": - 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].retrieve_pvtkey_req_id=="string" - && typeof res_obj.params[0].withdraw_id=="string") { + 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].retrieve_pvtkey_req_id == "string" && + typeof res_obj.params[0].withdraw_id == "string") { let shamirs_shares_response = res_obj.params[0]; let retrieve_pvtkey_req_id = res_obj.params[0].retrieve_pvtkey_req_id; let withdraw_id = res_obj.params[0].withdraw_id; - if(typeof btc_pvt_arr!=="object") btc_pvt_arr = []; - if (typeof btc_pvt_arr[retrieve_pvtkey_req_id]=="undefined") btc_pvt_arr[retrieve_pvtkey_req_id] = []; - btc_pvt_arr[retrieve_pvtkey_req_id].push(shamirs_shares_response); - if (btc_pvt_arr[retrieve_pvtkey_req_id].length===localbitcoinplusplus.master_configurations.ShamirsMaxShares) { + if (typeof btc_pvt_arr !== "object") btc_pvt_arr = []; + if (typeof btc_pvt_arr[retrieve_pvtkey_req_id] == "undefined") btc_pvt_arr[ + retrieve_pvtkey_req_id] = []; + btc_pvt_arr[retrieve_pvtkey_req_id].push(shamirs_shares_response); + if (btc_pvt_arr[retrieve_pvtkey_req_id].length === localbitcoinplusplus.master_configurations + .ShamirsMaxShares) { delete res_obj.params[0].private_key_chunk; - res_obj.params[0].btc_private_key_array = JSON.stringify(btc_pvt_arr[retrieve_pvtkey_req_id]); - RM_RPC.receive_rpc_response.call(this, JSON.stringify(res_obj)); - btc_pvt_arr[retrieve_pvtkey_req_id] = []; // Unset the object - } + res_obj.params[0].btc_private_key_array = JSON.stringify(btc_pvt_arr[ + retrieve_pvtkey_req_id]); + RM_RPC.receive_rpc_response.call(this, JSON.stringify(res_obj)); + btc_pvt_arr[retrieve_pvtkey_req_id] = []; // Unset the object + } } break; case "deposit_withdraw_user_claim": RM_RPC.filter_legit_requests(function (is_valid_request) { - if (is_valid_request !== true) return false; - if (typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY=="undefined") throw new Error("Supernode Private Keys is undefind."); - if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object") { - let user_claim_request = res_obj.params[0]; - let user_claim_id = user_claim_request.claim_id.split('!!'); - let withdraw_order_id = user_claim_id[0]; - let user_id = user_claim_id[1]; + if (is_valid_request !== true) return false; + if (typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY == + "undefined") throw new Error("Supernode Private Keys is undefind."); + if (typeof res_obj.params == "object" && typeof res_obj.params[0] == + "object") { + let user_claim_request = res_obj.params[0]; + let user_claim_id = user_claim_request.claim_id.split('!!'); + let withdraw_order_id = user_claim_id[0]; + let user_id = user_claim_id[1]; - let deposit_withdraw_user_claim_obj = { - claim_id:user_claim_request.claim_id - } + let deposit_withdraw_user_claim_obj = { + claim_id: user_claim_request.claim_id + } - let deposit_withdraw_user_claim_str = JSON.stringify(deposit_withdraw_user_claim_obj); - let deposit_withdraw_user_claim_hash = Crypto.SHA256(deposit_withdraw_user_claim_str); + let deposit_withdraw_user_claim_str = JSON.stringify( + deposit_withdraw_user_claim_obj); + let deposit_withdraw_user_claim_hash = Crypto.SHA256( + deposit_withdraw_user_claim_str); - if (deposit_withdraw_user_claim_hash==user_claim_request.hash && - RM_WALLET.verify(deposit_withdraw_user_claim_hash, - user_claim_request.sign, user_claim_request.userPubKey)) { - //If the request is valid, find out if the requester is depositor or withdrawer - - readDB("withdraw_cash", withdraw_order_id).then(async function(withdraw_data) { - if (typeof withdraw_data=="object") { - if (withdraw_data.depositor_flo_id==user_id) { - // Depositor claimed to deposit the cash - withdraw_data.status = 3; - updateinDB('withdraw_cash', withdraw_data, withdraw_data.id); - let update_withdraw_cash_obj_data = { - depositor_claim:withdraw_data - }; - let update_withdraw_cash_obj_data_str = JSON.stringify(update_withdraw_cash_obj_data); - let update_withdraw_cash_obj_data_hash = Crypto.SHA256(update_withdraw_cash_obj_data_str); - let update_withdraw_cash_obj_data_sign = RM_WALLET - .sign(update_withdraw_cash_obj_data_hash, localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY); - update_withdraw_cash_obj_data.hash = update_withdraw_cash_obj_data_hash; - update_withdraw_cash_obj_data.sign = update_withdraw_cash_obj_data_sign; - update_withdraw_cash_obj_data.publicKey = localbitcoinplusplus.wallets.my_local_flo_public_key; - let update_withdraw_cash_obj = RM_RPC - .send_rpc - .call(this, "update_all_withdraw_cash_depositor_claim", - update_withdraw_cash_obj_data); - doSend(update_withdraw_cash_obj); - } else if (withdraw_data.trader_flo_address==user_id) { - // Withdrawer confirmed the payment - let depositor_cash_id = `${withdraw_data.depositor_flo_id}_${withdraw_data.currency}`; - let withdrawer_cash_id = `${withdraw_data.trader_flo_address}_${withdraw_data.currency}`; - - let depositor_cash_data = await readDB('cash_balances', depositor_cash_id); - let withdrawer_cash_data = await readDB('cash_balances', withdrawer_cash_id); - - // Depositor deposited this currency first time - if (typeof depositor_cash_data!=="object" || typeof depositor_cash_data=="undefined") { - depositor_cash_data = {id: depositor_cash_id, cash_balance:0, trader_flo_address:withdraw_data.depositor_flo_id, currency:withdraw_data.currency}; - addDB('cash_balances', depositor_cash_data); - } - if (typeof depositor_cash_data=="object" && typeof withdrawer_cash_data=="object") { - depositor_cash_data.cash_balance += parseFloat(withdraw_data.withdraw_amount); - withdrawer_cash_data.cash_balance -= parseFloat(withdraw_data.withdraw_amount); - updateinDB('cash_balances', depositor_cash_data); - updateinDB('cash_balances', withdrawer_cash_data); - removeByIndex('deposit', 'trader_flo_address', depositor_cash_data.trader_flo_address); - removeinDB('withdraw_cash', withdraw_data.id); + if (deposit_withdraw_user_claim_hash == user_claim_request.hash && + RM_WALLET.verify(deposit_withdraw_user_claim_hash, + user_claim_request.sign, user_claim_request.userPubKey)) { + //If the request is valid, find out if the requester is depositor or withdrawer - let update_cash_balance_obj = { - depositor_cash_data:depositor_cash_data, - withdrawer_cash_data: withdrawer_cash_data - } - let update_cash_balance_str = JSON.stringify(update_cash_balance_obj); - let update_cash_balance_hash = Crypto.SHA256(update_cash_balance_str); - let update_cash_balance_sign = RM_WALLET - .sign(update_cash_balance_hash, localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY); - - update_cash_balance_obj.publicKey = localbitcoinplusplus.wallets.my_local_flo_public_key; - update_cash_balance_obj.sign = update_cash_balance_sign; - update_cash_balance_obj.hash = update_cash_balance_hash; - update_cash_balance_obj.withdraw_id = withdraw_data.id; - - let update_cash_balance_req = RM_RPC + readDB("withdraw_cash", withdraw_order_id).then(async function ( + withdraw_data) { + if (typeof withdraw_data == "object") { + if (withdraw_data.depositor_flo_id == user_id) { + // Depositor claimed to deposit the cash + withdraw_data.status = 3; + updateinDB('withdraw_cash', withdraw_data, + withdraw_data.id); + let update_withdraw_cash_obj_data = { + depositor_claim: withdraw_data + }; + let update_withdraw_cash_obj_data_str = + JSON.stringify( + update_withdraw_cash_obj_data); + let update_withdraw_cash_obj_data_hash = + Crypto.SHA256( + update_withdraw_cash_obj_data_str); + let update_withdraw_cash_obj_data_sign = + RM_WALLET + .sign( + update_withdraw_cash_obj_data_hash, + localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY + ); + update_withdraw_cash_obj_data.hash = + update_withdraw_cash_obj_data_hash; + update_withdraw_cash_obj_data.sign = + update_withdraw_cash_obj_data_sign; + update_withdraw_cash_obj_data.publicKey = + localbitcoinplusplus.wallets.my_local_flo_public_key; + let update_withdraw_cash_obj = RM_RPC .send_rpc - .call(this, "update_all_deposit_withdraw_success", - update_cash_balance_obj); - doSend(update_cash_balance_req); + .call(this, + "update_all_withdraw_cash_depositor_claim", + update_withdraw_cash_obj_data); + doSend(update_withdraw_cash_obj); + } else if (withdraw_data.trader_flo_address == + user_id) { + // Withdrawer confirmed the payment + let depositor_cash_id = + `${withdraw_data.depositor_flo_id}_${withdraw_data.currency}`; + let withdrawer_cash_id = + `${withdraw_data.trader_flo_address}_${withdraw_data.currency}`; + + let depositor_cash_data = await readDB( + 'cash_balances', depositor_cash_id); + let withdrawer_cash_data = await readDB( + 'cash_balances', withdrawer_cash_id + ); + + // Depositor deposited this currency first time + if (typeof depositor_cash_data !== "object" || + typeof depositor_cash_data == + "undefined") { + depositor_cash_data = { + id: depositor_cash_id, + cash_balance: 0, + trader_flo_address: withdraw_data + .depositor_flo_id, + currency: withdraw_data.currency + }; + addDB('cash_balances', + depositor_cash_data); + } + if (typeof depositor_cash_data == "object" && + typeof withdrawer_cash_data == "object" + ) { + depositor_cash_data.cash_balance += + parseFloat(withdraw_data.withdraw_amount); + withdrawer_cash_data.cash_balance -= + parseFloat(withdraw_data.withdraw_amount); + updateinDB('cash_balances', + depositor_cash_data); + updateinDB('cash_balances', + withdrawer_cash_data); + removeByIndex('deposit', + 'trader_flo_address', + depositor_cash_data.trader_flo_address + ); + removeinDB('withdraw_cash', + withdraw_data.id); + + let update_cash_balance_obj = { + depositor_cash_data: depositor_cash_data, + withdrawer_cash_data: withdrawer_cash_data + } + let update_cash_balance_str = JSON.stringify( + update_cash_balance_obj); + let update_cash_balance_hash = Crypto.SHA256( + update_cash_balance_str); + let update_cash_balance_sign = + RM_WALLET + .sign(update_cash_balance_hash, + localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY + ); + + update_cash_balance_obj.publicKey = + localbitcoinplusplus.wallets.my_local_flo_public_key; + update_cash_balance_obj.sign = + update_cash_balance_sign; + update_cash_balance_obj.hash = + update_cash_balance_hash; + update_cash_balance_obj.withdraw_id = + withdraw_data.id; + + let update_cash_balance_req = RM_RPC + .send_rpc + .call(this, + "update_all_deposit_withdraw_success", + update_cash_balance_obj); + doSend(update_cash_balance_req); + } } + return true; } - return true; - } - }); + }); + } } - } - }); + }); break; case "update_all_withdraw_cash_depositor_claim": - if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object") { - let depositor_claim_response_object = res_obj.params[0]; - let update_withdraw_cash_obj_data_res = { - depositor_claim:depositor_claim_response_object.depositor_claim - }; - let update_withdraw_cash_obj_data_res_str = JSON.stringify(update_withdraw_cash_obj_data_res); - let depositor_claim_response_data_hash = Crypto.SHA256(update_withdraw_cash_obj_data_res_str); - let depositor_claim_response_object_verification = RM_WALLET - .verify(depositor_claim_response_data_hash, depositor_claim_response_object.sign, depositor_claim_response_object.publicKey); - - if ((depositor_claim_response_data_hash==depositor_claim_response_object.hash) && (depositor_claim_response_object_verification==true)) { - updateinDB('withdraw_cash', depositor_claim_response_object.depositor_claim, depositor_claim_response_object.depositor_claim.id); - return true; + if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object") { + let depositor_claim_response_object = res_obj.params[0]; + let update_withdraw_cash_obj_data_res = { + depositor_claim: depositor_claim_response_object.depositor_claim + }; + let update_withdraw_cash_obj_data_res_str = JSON.stringify( + update_withdraw_cash_obj_data_res); + let depositor_claim_response_data_hash = Crypto.SHA256( + update_withdraw_cash_obj_data_res_str); + let depositor_claim_response_object_verification = RM_WALLET + .verify(depositor_claim_response_data_hash, depositor_claim_response_object.sign, + depositor_claim_response_object.publicKey); + + if ((depositor_claim_response_data_hash == depositor_claim_response_object.hash) && + (depositor_claim_response_object_verification == true)) { + updateinDB('withdraw_cash', depositor_claim_response_object.depositor_claim, + depositor_claim_response_object.depositor_claim.id); + return true; + } + return false; } - return false; - } break; case "update_all_deposit_withdraw_success": if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object") { let withdraw_success_response = res_obj.params[0]; let update_cash_balance_obj_res = { - depositor_cash_data:withdraw_success_response.depositor_cash_data + depositor_cash_data: withdraw_success_response.depositor_cash_data } let update_cash_balance_obj_res_str = JSON.stringify(update_cash_balance_obj_res); - let update_cash_balance_obj_res_hash = Crypto.SHA256(update_cash_balance_obj_res_str); + let update_cash_balance_obj_res_hash = Crypto.SHA256( + update_cash_balance_obj_res_str); let update_cash_balance_obj_res_verification = RM_WALLET - .verify(update_cash_balance_obj_res_hash, withdraw_success_response.sign, withdraw_success_response.publicKey); + .verify(update_cash_balance_obj_res_hash, withdraw_success_response.sign, + withdraw_success_response.publicKey); - 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.withdrawer_cash_data); - removeByIndex('deposit', 'trader_flo_address', withdraw_success_response.depositor_cash_data.trader_flo_address); + removeByIndex('deposit', 'trader_flo_address', withdraw_success_response.depositor_cash_data + .trader_flo_address); removeinDB('withdraw_cash', withdraw_success_response.withdraw_id); return true; } @@ -37995,68 +39942,75 @@ exports.createContext = Script.createContext = function (context) { case "add_user_public_data": RM_RPC.filter_legit_requests(function (is_valid_request) { - if (is_valid_request !== true) return false; + if (is_valid_request !== true) return false; - let supernode_flo_public_key = localbitcoinplusplus.wallets.my_local_flo_public_key; - if (!localbitcoinplusplus.master_configurations.supernodesPubKeys.includes(supernode_flo_public_key)) { - throw new Error("Failed to identify as supernode."); - } - - if (typeof res_obj.params == "object" && typeof res_obj.params[0] == "object") { - let req_data = res_obj.params[0].public_data; - try { - let flo_address = bitjs.FLO_TEST.pubkey2address(req_data.trader_flo_pubKey); - - if (flo_address==req_data.trader_flo_address && req_data.trader_flo_address.length>0) { - - let public_req_object = { - trader_flo_address: req_data.trader_flo_address, - trader_flo_pubKey: req_data.trader_flo_pubKey, - supernode_flo_public_key: supernode_flo_public_key, - trader_status: 0, - timestamp: + new Date() - } - - addDB('userPublicData', public_req_object); - - let public_req_object_str = JSON.stringify(public_req_object); - let public_req_object_hash = Crypto.SHA256(public_req_object_str); - let public_req_object_sign = RM_WALLET.sign(public_req_object_hash, localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY); - - let userPublicDataResponseObject = { - data: public_req_object, - data_hash: public_req_object_hash, - sign: public_req_object_sign, - su_pubKey: localbitcoinplusplus.wallets.my_local_flo_public_key - } - - let send_pvtkey_req = RM_RPC - .send_rpc - .call(this, "superNodeSignedAddUserPublicData", - userPublicDataResponseObject); - - doSend(send_pvtkey_req); - + let supernode_flo_public_key = localbitcoinplusplus.wallets.my_local_flo_public_key; + if (!localbitcoinplusplus.master_configurations.supernodesPubKeys.includes( + supernode_flo_public_key)) { + throw new Error("Failed to identify as supernode."); } - } catch (error) { - throw new Error('Invalid public key and flo address combination.'); - } - } - }); - break; + + if (typeof res_obj.params == "object" && typeof res_obj.params[0] == + "object") { + let req_data = res_obj.params[0].public_data; + try { + let flo_address = bitjs.FLO_TEST.pubkey2address(req_data.trader_flo_pubKey); + + if (flo_address == req_data.trader_flo_address && req_data.trader_flo_address + .length > 0) { + + let public_req_object = { + trader_flo_address: req_data.trader_flo_address, + trader_flo_pubKey: req_data.trader_flo_pubKey, + supernode_flo_public_key: supernode_flo_public_key, + trader_status: 0, + timestamp: +new Date() + } + + addDB('userPublicData', public_req_object); + + let public_req_object_str = JSON.stringify(public_req_object); + let public_req_object_hash = Crypto.SHA256( + public_req_object_str); + let public_req_object_sign = RM_WALLET.sign( + public_req_object_hash, localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY + ); + + let userPublicDataResponseObject = { + data: public_req_object, + data_hash: public_req_object_hash, + sign: public_req_object_sign, + su_pubKey: localbitcoinplusplus.wallets.my_local_flo_public_key + } + + let send_pvtkey_req = RM_RPC + .send_rpc + .call(this, "superNodeSignedAddUserPublicData", + userPublicDataResponseObject); + + doSend(send_pvtkey_req); + + } + } catch (error) { + throw new Error('Invalid public key and flo address combination.'); + } + } + }); + break; case "superNodeSignedAddUserPublicData": response_from_sever = RM_RPC.receive_rpc_response.call(this, - JSON.stringify(res_obj)); + JSON.stringify(res_obj)); doSend(JSON.stringify(response_from_sever)); // send response to client - break; + break; case "refresh_deposit_status_request": - RM_RPC.filter_legit_requests((is_valid_request)=>{ + RM_RPC.filter_legit_requests((is_valid_request) => { if (is_valid_request !== true) return false; readDBbyIndex("deposit", 'status', 1).then(function (res) { res.map(function (deposit_trade) { - if (localbitcoinplusplus.master_configurations.tradableAsset1.includes(deposit_trade.product)) { + if (localbitcoinplusplus.master_configurations.tradableAsset1 + .includes(deposit_trade.product)) { validateDepositedBTCBalance(deposit_trade); } }); @@ -38065,107 +40019,119 @@ exports.createContext = Script.createContext = function (context) { break; case "update_external_file_request": - RM_RPC.filter_legit_requests(is_valid_request=>{ + RM_RPC.filter_legit_requests(is_valid_request => { if (is_valid_request !== true) return false; let update_script_request = res_obj.params[0]; - if (typeof update_script_request.user_flo_address !=="string") throw new Error("Unknown user"); - - if(!localbitcoinplusplus.master_configurations.supernodesPubKeys - .includes(localbitcoinplusplus.wallets.my_local_flo_public_key)) throw new Error("Unauthorized server."); + if (typeof update_script_request.user_flo_address !== "string") throw new Error( + "Unknown user"); + + if (!localbitcoinplusplus.master_configurations.supernodesPubKeys + .includes(localbitcoinplusplus.wallets.my_local_flo_public_key)) throw new Error( + "Unauthorized server."); let server_pubkey = localbitcoinplusplus.wallets.my_local_flo_public_key; - if (typeof update_script_request.file_to_update=="string") { - readDB("external_files", update_script_request.file_to_update).then(file_details=>{ - if (typeof file_details.content=="string" && file_details.content.length>0) { - let file_details_string = JSON.stringify(file_details); + if (typeof update_script_request.file_to_update == "string") { + readDB("external_files", update_script_request.file_to_update).then( + file_details => { + if (typeof file_details.content == "string" && file_details + .content.length > 0) { + let file_details_string = JSON.stringify(file_details); + let server_sign = RM_WALLET + .sign(file_details_string, localbitcoinplusplus.wallets + .MY_SUPERNODE_PRIVATE_KEY); + response_from_sever = RM_RPC.send_rpc + .call(this, "update_external_file_server_response", { + user_flo_address: update_script_request.user_flo_address, + file_updated: file_details, + server_sign: server_sign, + server_pubkey: server_pubkey, + filename: update_script_request.file_to_update + }); + doSend(response_from_sever); + } + }); + } else { + readAllDB("external_files").then(file_details => { + if (file_details.length > 0) { + let file_details_str = JSON.stringify(file_details); let server_sign = RM_WALLET - .sign(file_details_string, localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY); + .sign(file_details_str, localbitcoinplusplus.wallets + .MY_SUPERNODE_PRIVATE_KEY); response_from_sever = RM_RPC.send_rpc .call(this, "update_external_file_server_response", { user_flo_address: update_script_request.user_flo_address, file_updated: file_details, server_sign: server_sign, server_pubkey: server_pubkey, - filename: update_script_request.file_to_update + filename: "UPDATE_ALL_FILES" }); doSend(response_from_sever); } }); - } else { - readAllDB("external_files").then(file_details=>{ - if (file_details.length>0) { - let file_details_str = JSON.stringify(file_details); - let server_sign = RM_WALLET - .sign(file_details_str, localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY); - response_from_sever = RM_RPC.send_rpc - .call(this, "update_external_file_server_response", { - user_flo_address: update_script_request.user_flo_address, - file_updated: file_details, - server_sign: server_sign, - server_pubkey: server_pubkey, - filename: "UPDATE_ALL_FILES" - }); - doSend(response_from_sever); - } - }); - } + } }); break; case "update_external_file_server_response": response_from_sever = RM_RPC.receive_rpc_response.call(this, - JSON.stringify(res_obj)); + JSON.stringify(res_obj)); doSend(JSON.stringify(response_from_sever)); // send response to client break; case "updateUserCryptoBalanceRequest": let updateUserCryptoBalanceResponseObject = res_obj.params[0]; - let SuPubKey = readDB(userPublicData, updateUserCryptoBalanceObject.trader_flo_address) - .then(user_data=>{ - if(typeof user_data !=="object" || user_data.supernode_flo_public_key.length<1) + let SuPubKey = readDB(userPublicData, updateUserCryptoBalanceResponseObject.trader_flo_address) + .then(user_data => { + if (typeof user_data !== "object" || user_data.supernode_flo_public_key.length < + 1) throw new Error(`No such user exists.`); - let updateUserCryptoBalanceResponseString = JSON.stringify - (updateUserCryptoBalanceResponseObject.updatedBTCBalanceObject); - let isBalanceLegit = RM_WALLET.verify(updateUserCryptoBalanceResponseString, + let updateUserCryptoBalanceResponseString = JSON.stringify( + updateUserCryptoBalanceResponseObject.updatedBTCBalanceObject); + let isBalanceLegit = RM_WALLET.verify(updateUserCryptoBalanceResponseString, updateUserCryptoBalanceResponseObject.updatedBTCBalanceObjectSign, - user_data.supernode_flo_public_key + user_data.supernode_flo_public_key ); if (isBalanceLegit) { updateinDB("crypto_balances", updateUserCryptoBalanceResponseObject.updatedBTCBalanceObject, - user_data.trader_flo_address); - if(localbitcoinplusplus.wallets.my_local_flo_address==updateUserCryptoBalanceObject.trader_flo_address) - displayBalances(updateUserCryptoBalanceObject.trader_flo_address); + user_data.trader_flo_address); + if (localbitcoinplusplus.wallets.my_local_flo_address == + updateUserCryptoBalanceResponseObject.trader_flo_address) { + displayBalances(updateUserCryptoBalanceResponseObject.trader_flo_address); + alert(`Your balance is updated.`); + } return true; - } else { console.warn(`Failed to update balance in your DB. Please refresh.`); } + } else { + console.warn(`Failed to update balance in your DB. Please refresh.`); + } }); break; case "addNewKbucketNode": - try { - const newKbucketObject = res_obj.params[0]; - localbitcoinplusplus.kademlia.addNewUserNodeInKbucket("FLO_TEST", - newKbucketObject.newKbucketNode.id, newKbucketObject.newKbucketNode.data); - } catch (error) { - console.error(error); - } + try { + const newKbucketObject = res_obj.params[0]; + localbitcoinplusplus.kademlia.addNewUserNodeInKbucket("FLO_TEST", + newKbucketObject.newKbucketNode.id, newKbucketObject.newKbucketNode.data); + } catch (error) { + console.error(error); + } break; case "queryKbucket": - try { - const kBucketQuery = res_obj.params[0]; - const kfrom = kBucketQuery.query.from; - const kto = kBucketQuery.query.to; - const kmsg = kBucketQuery.query.msg; + try { + const kBucketQuery = res_obj.params[0]; + const kfrom = kBucketQuery.query.from; + const kto = kBucketQuery.query.to; + const kmsg = kBucketQuery.query.msg; - buckId = localbitcoinplusplus.kademlia.floIdToKbucketId("FLO_TEST", kto); - const getItem = KBucket.get(buckId); - const getData = getItem.data; - - } catch (error) { - console.error(error); - } + buckId = localbitcoinplusplus.kademlia.floIdToKbucketId("FLO_TEST", kto); + const getItem = KBucket.get(buckId); + const getData = getItem.data; + + } catch (error) { + console.error(error); + } break; case "messageBroadcasting": @@ -38182,7 +40148,7 @@ exports.createContext = Script.createContext = function (context) { case "MessageForMiddleman": console.log(res_obj); break; - + default: break; } @@ -38205,12 +40171,11 @@ exports.createContext = Script.createContext = function (context) { } function writeToScreen(message) { - var pre = document.createElement("p"); - pre.style.wordWrap = "break-word"; - pre.innerHTML = message; + // var pre = document.createElement("p"); + // pre.style.wordWrap = "break-word"; + // pre.innerHTML = message; //output.appendChild(pre); - console.log(pre); - + console.log(message); } /* Websocket Code Ends Here*/ @@ -38273,7 +40238,7 @@ exports.createContext = Script.createContext = function (context) { id: null, trader_flo_address: null, crypto_balance: null, - crypto_currency:null + crypto_currency: null } const cash_balances = { @@ -38297,7 +40262,7 @@ exports.createContext = Script.createContext = function (context) { id: '', supernode_transaction_key: null } - + const supernode_private_key_chunks = { id: '', privateKeyChunks: null @@ -38311,7 +40276,7 @@ exports.createContext = Script.createContext = function (context) { receiverBTCEquivalentInCash: null, currency: null, product: null, - change_adress:null, + change_adress: null, timestamp: null } @@ -38398,7 +40363,8 @@ exports.createContext = Script.createContext = function (context) { } if (!db.objectStoreNames.contains('crypto_balances')) { var objectStore = db.createObjectStore("crypto_balances", { - keyPath: 'id', autoIncrement: false + keyPath: 'id', + autoIncrement: false }); objectStore.createIndex('trader_flo_address', 'trader_flo_address', { unique: false @@ -38409,7 +40375,8 @@ exports.createContext = Script.createContext = function (context) { } if (!db.objectStoreNames.contains('cash_balances')) { var objectStore = db.createObjectStore("cash_balances", { - keyPath: 'id', autoIncrement: false + keyPath: 'id', + autoIncrement: false }); objectStore.createIndex('trader_flo_address', 'trader_flo_address', { unique: false @@ -38498,7 +40465,7 @@ exports.createContext = Script.createContext = function (context) { } function readDB(tablename, id) { - return new Promise((resolve, reject)=>{ + return new Promise((resolve, reject) => { var transaction = db.transaction([tablename]); var objectStore = transaction.objectStore(tablename); var request = objectStore.get(id); @@ -38518,7 +40485,7 @@ exports.createContext = Script.createContext = function (context) { } function readDBbyIndex(tablename, index, indexValue) { - return new Promise((resolve, reject)=>{ + return new Promise((resolve, reject) => { var transaction = db.transaction([tablename]); var objectStore = transaction.objectStore(tablename); let response = []; @@ -38539,7 +40506,7 @@ exports.createContext = Script.createContext = function (context) { }; }); } - + function readAllDB(tablename) { return new Promise((resolve, reject) => { let response = []; @@ -38562,7 +40529,7 @@ exports.createContext = Script.createContext = function (context) { let store = request.objectStore(tablename) await store.add(dbObject); await request.complete; - console.info("Data added in "+tablename); + console.info("Data added in " + tablename); return dbObject; } catch (error) { return new Error(error); @@ -38594,12 +40561,12 @@ exports.createContext = Script.createContext = function (context) { } function removeByIndex(tablename, indexName, indexValue) { - return new Promise((resolve, reject)=>{ + return new Promise((resolve, reject) => { var request = db.transaction([tablename], "readwrite") - .objectStore(tablename); + .objectStore(tablename); var index = request.index(indexName); var request = index.openCursor(IDBKeyRange.only(indexValue)); - request.onsuccess = function() { + request.onsuccess = function () { var cursor = request.result; if (cursor) { cursor.delete(); @@ -38608,7 +40575,7 @@ exports.createContext = Script.createContext = function (context) { resolve(true); } }; - request.onerror = function(e) { + request.onerror = function (e) { reject(e); } }) @@ -38620,7 +40587,7 @@ exports.createContext = Script.createContext = function (context) { var objectStore = request.objectStore(tablename); 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); return tablename; } catch (error) { return new Error(error); @@ -38635,7 +40602,8 @@ exports.createContext = Script.createContext = function (context) { try { var rm_configs = localbitcoinplusplus.actions.fetch_configs(async function (...fetch_configs_res) { window.bitjs = []; // Launch bitjs - localbitcoinplusplus.master_configurations.tradableAsset1.map(asset=>bitjslib(asset)); + localbitcoinplusplus.master_configurations.tradableAsset1.map(asset => bitjslib( + asset)); init(); }); } catch (error) { @@ -38646,31 +40614,33 @@ exports.createContext = Script.createContext = function (context) { @@ -39215,7 +41206,7 @@ exports.createContext = Script.createContext = function (context) { if (typeof localbitcoinplusplus.wallets !== "undefined") { const RM_WALLET = new localbitcoinplusplus.wallets; let new_flo_keys = RM_WALLET.generateFloKeys(); - + let new_key_li = ''; Object.keys(new_flo_keys).forEach(function (key) { new_key_li += `
  • ${key}: ${new_flo_keys[key]}
  • `; @@ -39249,8 +41240,10 @@ exports.createContext = Script.createContext = function (context) { function randomNoRepeats(array) { var copy = array.slice(0); - return function() { - if (copy.length < 1) { copy = array.slice(0); } + return function () { + if (copy.length < 1) { + copy = array.slice(0); + } var index = Math.floor(Math.random() * copy.length); var item = copy[index]; copy.splice(index, 1); @@ -39259,17 +41252,18 @@ exports.createContext = Script.createContext = function (context) { } function duplicatesInArray(arr) { - arr.reduce(function(acc, el, i, arr) { - if (arr.indexOf(el) !== i && acc.indexOf(el) < 0) acc.push(el); return acc; + arr.reduce(function (acc, el, i, arr) { + if (arr.indexOf(el) !== i && acc.indexOf(el) < 0) acc.push(el); + return acc; }, []); - } + } /* Function to load files to db */ function readBlob(file_name) { var files = document.getElementById('upload_file_db').files; - if (!files.length) return('Please select a file!'); + if (!files.length) return ('Please select a file!'); if (typeof file_name !== "string") throw new Error('Please provide a valid file name.'); @@ -39280,7 +41274,7 @@ exports.createContext = Script.createContext = function (context) { var reader = new FileReader(); // If we use onloadend, we need to check the readyState. - reader.onloadend = function(evt) { + reader.onloadend = function (evt) { if (evt.target.readyState == FileReader.DONE) { // DONE == 2 let data = evt.target.result; let hash = Crypto.SHA256(data); @@ -39306,7 +41300,7 @@ exports.createContext = Script.createContext = function (context) { dbFileLabel.className += ` button bg-purple mg-5 `; const dbFile = document.createElement('input'); dbFile.className += ` hidden `; - dbFile.setAttribute("type", "file"); + dbFile.setAttribute("type", "file"); dbFile.setAttribute("id", "upload_file_db"); const readBytesButtons = document.createElement("input"); readBytesButtons.type = 'button'; @@ -39318,8 +41312,8 @@ exports.createContext = Script.createContext = function (context) { d3div.appendChild(dbFileLabel); d3div.appendChild(readBytesButtons); d3div.appendChild(fileUploadDiv); - - document.querySelector('#uploadFileButton').addEventListener('click', function(evt) { + + document.querySelector('#uploadFileButton').addEventListener('click', function (evt) { if (evt.target.tagName.toLowerCase() == 'button') { let fname = prompt("Enter name of this file."); readBlob(fname); @@ -39335,15 +41329,15 @@ exports.createContext = Script.createContext = function (context) { //Function to check current balance of a BTC address function validateDepositedBTCBalance(trader_deposits) { if (!localbitcoinplusplus.master_configurations.supernodesPubKeys - .includes(localbitcoinplusplus.wallets.my_local_flo_public_key) - && typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY !== "string" - ) return false; + .includes(localbitcoinplusplus.wallets.my_local_flo_public_key) && + typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY !== "string" + ) return false; if (!localbitcoinplusplus.master_configurations.tradableAsset1 .includes(trader_deposits.product)) return false; let explorer; switch (trader_deposits.product) { case "BTC": - explorer = localbitcoinplusplus.server.btc_mainnet; + explorer = localbitcoinplusplus.server.btc_mainnet; break; case "BTC_TEST": explorer = localbitcoinplusplus.server.btc_testnet; @@ -39359,17 +41353,17 @@ exports.createContext = Script.createContext = function (context) { } try { let url = `${explorer}/api/addr/${trader_deposits.btc_address}/balance`; - helper_functions.ajaxGet(url).then(balance=> { + helper_functions.ajaxGet(url).then(balance => { if (!isNaN(balance) && parseFloat(balance) > 0) { balance = parseFloat(balance); /************************ Case of dispute *****************/ - if(0) { - //if (trader_deposits.bitcoinToBePaid - balance > localbitcoinplusplus.master_configurations.btcTradeMargin) { + if (0) { + //if (trader_deposits.bitcoinToBePaid - balance > localbitcoinplusplus.master_configurations.btcTradeMargin) { console.log(trader_deposits.bitcoinToBePaid, balance, localbitcoinplusplus.master_configurations .btcTradeMargin); console.warn("User sent less cryptos"); - + //trader_deposits.status = 4; // User sent less BTC than he should #Disputed //updateinDB("deposit", trader_deposits, trader_deposits.trader_flo_address); } else { @@ -39378,16 +41372,19 @@ exports.createContext = Script.createContext = function (context) { trader_deposits.status = 2; updateinDB("deposit", trader_deposits, trader_deposits.trader_flo_address); - readDBbyIndex('system_btc_reserves_private_keys', 'btc_address', trader_deposits.btc_address).then(function(reserve_res) { - if (typeof reserve_res=="object") { - reserve_res.map(reserves=>{ - reserves.balance = balance; - updateinDB('system_btc_reserves_private_keys', reserves, reserves.id); - }); - } - }); + readDBbyIndex('system_btc_reserves_private_keys', 'btc_address', trader_deposits.btc_address) + .then(function (reserve_res) { + if (typeof reserve_res == "object") { + reserve_res.map(reserves => { + reserves.balance = balance; + updateinDB('system_btc_reserves_private_keys', reserves, + reserves.id); + }); + } + }); - let trader_depositor_cash_id = `${trader_deposits.trader_flo_address}_${trader_deposits.product}`; + let trader_depositor_cash_id = + `${trader_deposits.trader_flo_address}_${trader_deposits.product}`; let updatedCryptobalances = { id: trader_depositor_cash_id, trader_flo_address: trader_deposits.trader_flo_address, @@ -39396,32 +41393,36 @@ exports.createContext = Script.createContext = function (context) { } readDB('crypto_balances', trader_depositor_cash_id).then(function (res_btc_balances) { if (typeof res_btc_balances == "object" && typeof res_btc_balances.result == - "object" && typeof res_btc_balances.crypto_balance=="number") { - updatedCryptobalances.crypto_balance += parseFloat(res_btc_balances.crypto_balance); + "object" && typeof res_btc_balances.crypto_balance == "number") { + updatedCryptobalances.crypto_balance += parseFloat(res_btc_balances + .crypto_balance); } // Update crypto balance of user in crypto_balances updateinDB("crypto_balances", updatedCryptobalances, trader_deposits.btc_address) - .then(updatedBTCBalanceObject=>{ + .then(updatedBTCBalanceObject => { - const RM_WALLET = new localbitcoinplusplus.wallets; - const RM_RPC = new localbitcoinplusplus.rpc; + const RM_WALLET = new localbitcoinplusplus.wallets; + const RM_RPC = new localbitcoinplusplus.rpc; - let updatedBTCBalanceObjectString = JSON.stringify(updatedCryptobalances); - let updatedBTCBalanceObjectSign = RM_WALLET - .sign(updatedBTCBalanceObjectString, localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY); + let updatedBTCBalanceObjectString = JSON.stringify( + updatedCryptobalances); + let updatedBTCBalanceObjectSign = RM_WALLET + .sign(updatedBTCBalanceObjectString, + localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY + ); - let updateUserCryptoBalanceObject = { - updatedBTCBalanceObject:updatedBTCBalanceObject, - updatedBTCBalanceObjectSign:updatedBTCBalanceObjectSign, - trader_flo_address: trader_deposits.trader_flo_address - } + let updateUserCryptoBalanceObject = { + updatedBTCBalanceObject: updatedBTCBalanceObject, + updatedBTCBalanceObjectSign: updatedBTCBalanceObjectSign, + trader_flo_address: trader_deposits.trader_flo_address + } - let updateUserCryptoBalanceRequestObject = RM_RPC + let updateUserCryptoBalanceRequestObject = RM_RPC .send_rpc("updateUserCryptoBalanceRequest", - updateUserCryptoBalanceObject); - doSend(updateUserCryptoBalanceRequestObject); + updateUserCryptoBalanceObject); + doSend(updateUserCryptoBalanceRequestObject); - }); + }); }); } @@ -39432,10 +41433,36 @@ exports.createContext = Script.createContext = function (context) { return false; } } + + function modalWindow(message) { + + var modal = document.getElementById('myModal'); + + var msg = document.getElementById("modal_msg"); + msg.innerHTML = message; + + // Get the element that closes the modal + var span = document.getElementsByClassName("close")[0]; + + // When the user clicks on (x), close the modal + span.onclick = function () { + modal.style.display = "none"; + } + + // When the user clicks anywhere outside of the modal, close it + window.onclick = function (event) { + if (event.target == modal) { + modal.style.display = "none"; + } + } + + modal.style.display = "block"; + + } - -