diff --git a/cash_payments_handler.html b/cash_payments_handler.html index f144bfb..12e462c 100644 --- a/cash_payments_handler.html +++ b/cash_payments_handler.html @@ -12016,7 +12016,6 @@ // 03F7493F11B8E44B9798CD434D20FBE7FA34B9779D144984889D11A17C56A18742,039B4AA00DBFC0A6631DE6DA83526611A0E6B857D3579DF840BBDEAE8B6898E3B6, // 03C8E3836C9A77E2AF03D4265D034BA85732738919708EAF6A16382195AE796EDF,0349B08AA1ABDCFFB6D78CD7C949665AD2FF065EA02B3C6C47A5E9592C9A1C6BCB, // 026FCC6CFF6EB3A39E54BEB6E13FC2F02C3A93F4767AA80E49E7E876443F95AE5F, - // #!#externalFiles={"d3js":"58f54395efa8346e8e94d12609770f66b916897e7f4e05f6c98780cffa5c70a3"} // #!#cashiers={"032871A74D2DDA9D0DE7135F58B5BD2D7F679D2CCA20EA7909466D1A6912DF4022":"johnDoe@upi", // "03DB4A12EB543B293DDBB0CE314C46C36D6761294AFBB7264A6D78F710FFD97CF0":"janeDoe@upi"} // #!#ShamirsMaxShares=8#!#supernodeSeeds={"ranchimall1":{"ip":"127.0.0.1:9111","kbucketId":"oZxHcbSf1JC8t5GjutopWYXs7C6Fe9p7ps"}, @@ -12028,16 +12027,17 @@ text = `masterFLOPubKey=03EA5E2CAB18DA585400D6EC569438D415FAF200528E05D0E2B9BEAA2B5C3DCA90 - #!#tradableAsset1=BTC,FLO,BTC_TEST,FLO_TEST#!#tradableAsset2=INR,USD, - #!#validTradingAmount=10,50,100,#!#btcTradeMargin=5000 - #!#MaxBackups=1 - #!#miners_fee={"btc":0.0003, "flo":0.0003} - #!#supernodesPubKeys=026FCC6CFF6EB3A39E54BEB6E13FC2F02C3A93F4767AA80E49E7E876443F95AE5F, - #!#cashiers={"032871A74D2DDA9D0DE7135F58B5BD2D7F679D2CCA20EA7909466D1A6912DF4022":"johnDoe@upi", - "03DB4A12EB543B293DDBB0CE314C46C36D6761294AFBB7264A6D78F710FFD97CF0":"janeDoe@upi"} - #!#ShamirsMaxShares=8#!#supernodeSeeds={ - "ranchimall6":{"ip":"127.0.0.1:9116","kbucketId":"oV1wCeWca3VawbBTfUGKA7Vd368PATnKAx"} - }`; + #!#tradableAsset1=BTC,FLO,BTC_TEST,FLO_TEST#!#tradableAsset2=INR,USD, + #!#validTradingAmount=10,50,100,#!#btcTradeMargin=5000 + #!#MaxBackups=1 + #!#ordersLife={"trade":300000, "cryptoDeposit":900000, "cryptoWithdraw":300000, "cashDeposit":900000, "cashWithdraw":900000} + #!#miners_fee={"btc":0.0005, "flo":0.001} + #!#supernodesPubKeys=0315C3A20FE7096CC2E0F81A80D5F1A687B8F9EFA65242A0B0881E1BA3EE7D7D53, + 026FCC6CFF6EB3A39E54BEB6E13FC2F02C3A93F4767AA80E49E7E876443F95AE5F, + #!#cashiers={"032871A74D2DDA9D0DE7135F58B5BD2D7F679D2CCA20EA7909466D1A6912DF4022":{"upi":"johnDoe@upi", "currencies":["INR"], "is_live":false}, + "03DB4A12EB543B293DDBB0CE314C46C36D6761294AFBB7264A6D78F710FFD97CF0":{"upi":"janeDoe@upi", "currencies":["INR", "USD"], "is_live":false}} + #!#ShamirsMaxShares=8#!#supernodeSeeds={"ranchimall1":{"ip":"127.0.0.1:9111","kbucketId":"oZxHcbSf1JC8t5GjutopWYXs7C6Fe9p7ps"}, + "ranchimall6":{"ip":"127.0.0.1:9116","kbucketId":"oV1wCeWca3VawbBTfUGKA7Vd368PATnKAx"}}`; return callback(text); if(ENVR==='LIVE') { @@ -13890,6 +13890,7 @@ Array.from(recv_deposit_btn).forEach(function(element) { element.addEventListener("click", async function(evt) { let btn = this; + btn.disabled = true; evt.preventDefault(); const deposit_id = this.value; const req_info = document.getElementById(`depositSpan${deposit_id}`); @@ -13900,7 +13901,7 @@ const depositorInfo = document.getElementById(`tr_${deposit_id}`); const depositorInfoVals = depositorInfo.getElementsByTagName('td'); const token_transfer_statement = `transfer ${depositorInfoVals[2].innerText} rupee# on behalf of ${depositorInfoVals[1].innerText}`; - const tx_amount = 0.001; + const tx_amount = 0.01; if(typeof websocket_name!=="string" || typeof requesting_supernode!=="string") return; @@ -13947,6 +13948,7 @@ flo_txid = resp_obj.txid.result || resp_obj.txid; } if (typeof flo_txid!=="string" || flo_txid.length < 1) return; + let req_body = { trader_flo_address: @@ -14018,9 +14020,10 @@ Array.from(recv_deposit_btn).forEach(function(element) { - element.addEventListener("click", function(evt) { + element.addEventListener("click", async function(evt) { evt.preventDefault(); let btn = this; + btn.disabled = true; const withdraw_id = this.value; const req_info = document.getElementById(`withdrawSpan${withdraw_id}`); const req_info_arr = req_info.value.split("_"); @@ -14049,7 +14052,7 @@ if(closest_live_su=='') closest_live_su = requesting_supernode; - const websocket_conn = localbitcoinplusplus.supernode_conns[closestSuList]; + const websocket_conn = localbitcoinplusplus.supernode_conns[closest_live_su]; if(typeof websocket_conn!=="object") return; RM_RPC.send_rpc @@ -14072,7 +14075,7 @@ return true; - }.bind(btn)); + }); }); } @@ -14183,6 +14186,27 @@ showMessage( `Connection successfull. Welocome to Local Bitcoin Plus Plus Cash Handling platform.` ); + + // https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload + window.addEventListener('beforeunload', function (e) { + e.preventDefault(); + delete e['returnValue']; + const RM_RPC = new localbitcoinplusplus.rpc; + + for(let conns in localbitcoinplusplus.supernode_conns) { + let req_body = { + trader_flo_address: + localbitcoinplusplus.wallets.my_local_flo_address, + is_live: false, + receiver_flo_address: conns + } + const server_con = localbitcoinplusplus.supernode_conns[conns]; + RM_RPC.send_rpc + .call(this, 'cashier_left', req_body) + .then(resp => doSend(server_con, resp)); + } + }); + }); } catch (e) { showMessage( diff --git a/index.html b/index.html index a3b536e..17783f6 100644 --- a/index.html +++ b/index.html @@ -1,682 +1,2656 @@ -
- - - -- Event information log - ===================== --
Welcome to RanchiMall Crypto exchange Local Bitcoin++
+ ++ Don't have private key, get it from here. +
+Please pay the amount to following address:
-${resp.msg}
`; - showMessage(counterTraderAccountAddress); - modalWindow(counterTraderAccountAddress); + document.getElementById("server_deposit_crypto_addr") + .innerText = resp.data.btc_address; + let counterTraderAccountAddress = resp.msg; + showMessage(counterTraderAccountAddress); + notify(counterTraderAccountAddress); } }); } @@ -24037,18 +26054,19 @@ ) ) { - readDB("localbitcoinUser", "00-01").then(function(user) { + readDB("localbitcoinUser", "00-01").then(function(user) { if ( typeof user == "object" && (user.myLocalFLOAddress == resp.data.trader_flo_address || user.myLocalFLOAddress == resp.receiver_flo_address) ) { let counterTraderAccountAddress = `Please pay ${resp.data.currency} ${resp.data.depositing_amount} to following UPI ID: - ${resp.msg}`; - showMessage(counterTraderAccountAddress); - modalWindow(counterTraderAccountAddress); + ${resp.msg}`; + showMessage(counterTraderAccountAddress); + notify(counterTraderAccountAddress); } - }); + }); + } } break; @@ -24182,10 +26200,13 @@ ); Promise.all([pr1,pr2,pr3,pr4]).then(()=>{ - // Update balances - displayBalances( - localbitcoinplusplus.wallets.my_local_flo_address - ); + displayTradeOrders(localbitcoinplusplus.wallets.my_local_flo_address); + // Update balances + displayBalances( + localbitcoinplusplus.wallets.my_local_flo_address + ); + notify("Trade successfull. Balances updated.") + showMessage("Trade successfull. Balances updated.") }) .catch(e => {throw new Error(e)}); @@ -24352,6 +26373,8 @@ .includes(res_obj.nodePubKey) || typeof localbitcoinplusplus.newBackupDatabase.db[res_obj.params[0].db_inst] !== "object" + || !localbitcoinplusplus.master_configurations.supernodesPubKeys + .includes(localbitcoinplusplus.wallets.my_local_flo_public_key) ) return; @@ -24373,82 +26396,177 @@ }); } break; - case "retrieve_shamirs_secret_btc_pvtkey": + case "delete_shamirs_secret_btc_pvtkey": if ( + typeof res_obj.params == "object" && + typeof res_obj.params[0] == "object" + ) { + if ( + typeof res_obj.nodePubKey != "string" + || !localbitcoinplusplus.master_configurations.supernodesPubKeys + .includes(res_obj.nodePubKey) + || typeof localbitcoinplusplus.newBackupDatabase.db[res_obj.params[0].db_inst] + !== "object" + || !localbitcoinplusplus.master_configurations.supernodesPubKeys + .includes(localbitcoinplusplus.wallets.my_local_flo_public_key) + ) + return; + + localbitcoinplusplus.newBackupDatabase.db[res_obj.params[0].db_inst] + .backup_removeinDB( + "supernode_private_key_chunks", + res_obj.params[0].chunk_val + ); + } + 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" && + "string" && typeof res_obj.params[0].withdraw_id == "string" && typeof res_obj.params[0].db_inst == "string" && typeof localbitcoinplusplus.wallets.my_local_flo_address == - "string" && + "string" && res_obj.params[0].receiver_flo_address === - localbitcoinplusplus.wallets.my_local_flo_address - ) { + localbitcoinplusplus.wallets.my_local_flo_address + ) { // This message was for Primary Supernode and is meant to be run in onMessage() - if ( - res_obj.params[0].db_inst == - localbitcoinplusplus.wallets.my_local_flo_address - ) - return; + if (res_obj.params[0].db_inst == + localbitcoinplusplus.wallets.my_local_flo_address + ) return; let shamirs_shares_response = res_obj.params[0]; let retrieve_pvtkey_req_id = - res_obj.params[0].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] = []; + if (typeof btc_pvt_arr[retrieve_pvtkey_req_id] == "undefined") { + btc_pvt_arr[retrieve_pvtkey_req_id] = []; + localbitcoinplusplus.actions.delay(15*60*1000) + .then(()=>{ + if(typeof btc_pvt_arr[retrieve_pvtkey_req_id]=="object") { + btc_pvt_arr[retrieve_pvtkey_req_id] = null; + } + }); + } + // Filter function below logic source - // https://stackoverflow.com/a/9229821/5348972 let seen_chunk_id_list = []; btc_pvt_arr[retrieve_pvtkey_req_id].filter(function(item) { - if (typeof item.private_key_chunk !== "undefined") { - return seen_chunk_id_list.hasOwnProperty( - item.private_key_chunk.id - ) - ? false - : seen_chunk_id_list.push(item.private_key_chunk.id); + if(typeof item.private_key_chunk=="object" && + typeof item.private_key_chunk.id=="string" && + !seen_chunk_id_list.hasOwnProperty( + item.private_key_chunk.id + ) ) { + return seen_chunk_id_list.push(item.private_key_chunk.id); } }); if ( - !seen_chunk_id_list.includes( + !seen_chunk_id_list.includes( shamirs_shares_response.private_key_chunk.id - ) && - typeof shamirs_shares_response.private_key_chunk.id == + ) && + typeof shamirs_shares_response.private_key_chunk.id == "string" ) { - btc_pvt_arr[retrieve_pvtkey_req_id].push( + btc_pvt_arr[retrieve_pvtkey_req_id].push( shamirs_shares_response - ); + ); } if ( - btc_pvt_arr[retrieve_pvtkey_req_id].length === - localbitcoinplusplus.master_configurations + 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] - ); - res_obj.params[0].trader_flo_address = - localbitcoinplusplus.wallets.my_local_flo_address; - RM_RPC.backup_receive_rpc_response.call( - this, - JSON.stringify(res_obj) - ); + const backup_server_db_instance = + localbitcoinplusplus.newBackupDatabase.db[primarySupernodeOfThisUser]; - localbitcoinplusplus.actions.delay(300000).then(() => { - btc_pvt_arr[retrieve_pvtkey_req_id] = []; // Unset the object - }); + if (typeof backup_server_db_instance !== "object") { + let backup_db_error_msg = `WARNING: Unknown DB instance. DB Backup failed.`; + throw new Error(backup_db_error_msg); } - } + delete res_obj.params[0].private_key_chunk; + let btc_pk_shares_array = btc_pvt_arr[retrieve_pvtkey_req_id] + .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); + const btc_reserves = await backup_server_db_instance + .backup_readDB("system_btc_reserves_private_keys", retrieve_pvtkey_req_id); + if (typeof btc_reserves !== "object") { + console.warn(`Record for ${retrieve_pvtkey_req_id} not found in system_btc_reserves_private_keys`); + break; + } + + let transaction_key = localbitcoinplusplus.actions + .master_decrypt(btc_reserves.supernode_transaction_key); + if(typeof transaction_key=="string") { + transaction_key = JSON.parse(transaction_key); + } + if (transaction_key.length <= 0) { + console.warn(`Failed to build tx key for ${retrieve_pvtkey_req_id} in system_btc_reserves_private_keys`); + break; + } + let btc_private_key = RM_WALLET.rebuild_private_key( + btc_pk_shares_array, + transaction_key + ); + if (btc_private_key.length <= 0) { + console.warn(`Failed to build private key for ${retrieve_pvtkey_req_id} in system_btc_reserves_private_keys`); + break; + } + console.log(btc_private_key); + + const withdraw_res = await backup_server_db_instance + .backup_readDB("withdraw_btc", withdraw_id); + if(typeof withdraw_res=="object" + && typeof withdraw_res.utxo_addr=="object") { + const RM_WALLET = new localbitcoinplusplus.wallets; + let crypto_addr_gen = RM_WALLET.generateFloKeys(btc_private_key, withdraw_res.product); + let crypto_addr = crypto_addr_gen.address; + if(!Object.values(withdraw_res.utxo_addr).includes(crypto_addr)) { + console.warn(`${crypto_addr} deposit address not present in withdraw id ${withdraw_id}`); + break; + } + + if(typeof localbitcoinplusplus.btc_private_key_array!=="object" + || Object.keys(localbitcoinplusplus.btc_private_key_array).length==0) { + localbitcoinplusplus.btc_private_key_array={}; + } + if(typeof localbitcoinplusplus.btc_private_key_array[withdraw_id] !== "object" + || localbitcoinplusplus.btc_private_key_array[withdraw_id]==null) { + localbitcoinplusplus.btc_private_key_array[withdraw_id] = []; + } + localbitcoinplusplus.btc_private_key_array[withdraw_id].push(btc_private_key); + + if(localbitcoinplusplus.btc_private_key_array[withdraw_id].length + ===Object.values(withdraw_res.utxo_addr).length) { + // When all the private keys are built successfully proceed further + res_obj.params[0].btc_private_key_array = + localbitcoinplusplus.btc_private_key_array[withdraw_id]; + + res_obj.params[0].trader_flo_address = withdraw_res.trader_flo_address; + RM_RPC.backup_receive_rpc_response.call( + this, + JSON.stringify(res_obj) + ); + if(!delete localbitcoinplusplus.btc_private_key_array[withdraw_id]) { + localbitcoinplusplus.btc_private_key_array[withdraw_id] = null; + } + } + + } + btc_pvt_arr = Object.keys(btc_pvt_arr).filter(f=>f!==retrieve_pvtkey_req_id); + } + } break; case "update_all_new_cash_withdraw_recorded_in_db": @@ -24708,12 +26826,12 @@ displayBalances( updateUserDepositsResponseObject.trader_flo_address ); - showMessage(`INFO: Your balance is updated.`); + notify(`INFO: Your balance is updated.`); } return true; }) } else { - showMessage( + notify( `WARNING: Failed to update balance in your DB. Please refresh.` ); } @@ -25165,22 +27283,18 @@ ); } - if (typeof res_data.deposit_data == "object") - _updateinDB( - "deposit", - res_data.deposit_data, - res_data.deposit_data.id, - true, - false - ); - if (typeof res_data.btc_reserve_data == "object") - _updateinDB( - "system_btc_reserves_private_keys", - res_data.btc_reserve_data, - res_data.btc_reserve_data.id.id, - true, - false - ); + if (typeof res_data.deposit_data == "object") { + for (const deposits of res_data.deposit_data) { + _updateinDB( + "deposit", + deposits, + deposits.id, + true, + false + ); + } + } + } } catch (e) { console.error(e); @@ -25219,13 +27333,11 @@ } if (typeof res_data.withdraw_btc_id == "string") _removeinDB("withdraw_btc", res_data.withdraw_btc_id); - if (typeof res_data.deposit_id == "string") - _removeinDB("deposit", res_data.deposit_id); - if (typeof res_data.btc_reserve_id == "string") - _removeinDB( - "system_btc_reserves_private_keys", - res_data.btc_reserve_id - ); + if(typeof res_data.deposit_id=="string") + _removeinDB("deposit", res_data.deposit_id); + if(typeof res_data.reserves_id=="string") + _removeinDB("system_btc_reserves_private_keys", + res_data.reserves_id); } } catch (e) { console.error(e); @@ -25524,20 +27636,6 @@ false ); } - backup_server_db_instance - .backup_readDB("localbitcoinUser", "00-01") - .then(function(user) { - if ( - typeof user == "object" && - user.myLocalFLOAddress == - resp.data.trader_flo_address - ) { - let counterTraderAccountAddress = `Please pay the amount to following address:
-${resp.msg}
`; - showMessage(counterTraderAccountAddress); - modalWindow(counterTraderAccountAddress); - } - }); } } } @@ -25588,7 +27686,8 @@ ); // Delete the request after 24 hours - localbitcoinplusplus.actions.delay(24 * 60 * 60 * 1000).then(function() { + let cash_order_life = JSON.parse(localbitcoinplusplus.master_configurations.ordersLife); + localbitcoinplusplus.actions.delay(cash_order_life.cashDeposit).then(function() { backup_server_db_instance.backup_removeinDB("cash_deposits", resp.data.id); }); @@ -25644,10 +27743,12 @@ ); break; - case "cancel_trade": + case "cancel_trade_in_backup": if ( typeof res_obj.params !== "object" || - typeof res_obj.params[0] !== "object" + typeof res_obj.params[0] !== "object" || + !localbitcoinplusplus.master_configurations.supernodesPubKeys + .includes(res_obj.nodePubKey) ) return; let cancel_res_data = res_obj.params[0]; @@ -25659,7 +27760,7 @@ typeof res_obj.params == "object" && typeof res_obj.params[0] == "object" ) { - let cancel_request = res_obj.params[0]; + let cancel_request = cancel_res_data.cancel_trade_obj; if (cancel_request.job == "cancel_trade_request") { let getPrimarySuObj = await localbitcoinplusplus.kademlia.determineClosestSupernode( cancel_res_data.trader_flo_address @@ -25672,7 +27773,6 @@ if (typeof backup_server_db_instance !== "object") { let backup_db_error_msg = `WARNING: Unknown DB instance. DB Backup failed.`; - showMessage(backup_db_error_msg); throw new Error(backup_db_error_msg); } tradeDB = @@ -25683,14 +27783,14 @@ RM_WALLET.verify( cancel_request.trade_id, cancel_request.signed_trade_id, - nodePubKey.trader_flo_pubKey + cancel_res_data.trader_flo_pubkey ) ) { backup_server_db_instance .backup_removeinDB( tradeDB, cancel_request.trade_id - ) + ); } } } @@ -25808,12 +27908,7 @@ false ); - Promise.all([b1,b2,b3,b4]).then(()=>{ - // Update balances - displayBalances( - localbitcoinplusplus.wallets.my_local_flo_address - ); - }) + Promise.all([b1,b2,b3,b4]) .catch(e => {throw new Error(e)}); } catch (error) { @@ -26174,6 +28269,8 @@ .includes(res_obj.nodePubKey) || typeof localbitcoinplusplus.newBackupDatabase.db[res_obj.params[0].db_inst] !== "object" + || !localbitcoinplusplus.master_configurations.supernodesPubKeys + .includes(localbitcoinplusplus.wallets.my_local_flo_public_key) ) return; @@ -26197,6 +28294,30 @@ } break; + case "delete_shamirs_secret_btc_pvtkey": + if ( + typeof res_obj.params == "object" && + typeof res_obj.params[0] == "object" + ) { + if ( + typeof res_obj.nodePubKey != "string" + || !localbitcoinplusplus.master_configurations.supernodesPubKeys + .includes(res_obj.nodePubKey) + || typeof localbitcoinplusplus.newBackupDatabase.db[res_obj.params[0].db_inst] + !== "object" + || !localbitcoinplusplus.master_configurations.supernodesPubKeys + .includes(localbitcoinplusplus.wallets.my_local_flo_public_key) + ) + return; + + localbitcoinplusplus.newBackupDatabase.db[res_obj.params[0].db_inst] + .backup_removeinDB( + "supernode_private_key_chunks", + res_obj.params[0].chunk_val + ); + } + break; + case "store_shamirs_secret_pvtkey_shares": if ( typeof res_obj.params == "object" && @@ -26238,12 +28359,6 @@ res_obj.params[0].receiver_flo_address === localbitcoinplusplus.wallets.my_local_flo_address ) { - // This message was for Primary Supernode and is meant to be run in onMessage() - // if ( - // res_obj.params[0].db_inst == - // localbitcoinplusplus.wallets.my_local_flo_address - // ) - // return; let shamirs_shares_response = res_obj.params[0]; let retrieve_pvtkey_req_id = @@ -26252,8 +28367,15 @@ 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] = []; + localbitcoinplusplus.actions.delay(15*60*1000) + .then(()=>{ + if(typeof btc_pvt_arr[retrieve_pvtkey_req_id]=="object") { + btc_pvt_arr[retrieve_pvtkey_req_id] = null; + } + }); + } // Filter function below logic source - // https://stackoverflow.com/a/9229821/5348972 @@ -26267,7 +28389,6 @@ ) ) { return seen_chunk_id_list.push(item.private_key_chunk.id); } - }); if ( @@ -26288,31 +28409,111 @@ .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] + + let btc_pk_shares_array = btc_pvt_arr[retrieve_pvtkey_req_id] + .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); + + let _readDB = readDB; + let _readDBbyIndex = readDBbyIndex; + let _updateinDB = updateinDB; + + if(shamirs_shares_response.db_inst!==localbitcoinplusplus.wallets.my_local_flo_address) { + if (typeof localbitcoinplusplus.newBackupDatabase.db[shamirs_shares_response.db_inst] == + "object") { + const foreign_db = + localbitcoinplusplus.newBackupDatabase.db[shamirs_shares_response.db_inst]; + _readDB = foreign_db.backup_readDB.bind(foreign_db); + _readDBbyIndex = foreign_db.backup_readDBbyIndex.bind(foreign_db); + _updateinDB = foreign_db.backup_updateinDB.bind(foreign_db); + } else { + err_msg = `WARNING: Invalid Backup DB Instance Id: ${shamirs_shares_response.db_inst}.`; + showMessage(err_msg); + throw new Error(err_msg); + } + } + + const btc_reserves = await _readDB("system_btc_reserves_private_keys", retrieve_pvtkey_req_id); + if (typeof btc_reserves !== "object") { + console.warn(`Record for ${retrieve_pvtkey_req_id} not found in system_btc_reserves_private_keys`); + break; + } + + let transaction_key = localbitcoinplusplus.actions + .master_decrypt(btc_reserves.supernode_transaction_key); + if(typeof transaction_key=="string") { + transaction_key = JSON.parse(transaction_key); + } + if (transaction_key.length <= 0) { + console.warn(`Failed to build tx key for ${retrieve_pvtkey_req_id} in system_btc_reserves_private_keys`); + break; + } + let btc_private_key = RM_WALLET.rebuild_private_key( + btc_pk_shares_array, + transaction_key ); - res_obj.params[0].trader_flo_address = - localbitcoinplusplus.wallets.my_local_flo_address; + if (btc_private_key.length <= 0) { + console.warn(`Failed to build private key for ${retrieve_pvtkey_req_id} in system_btc_reserves_private_keys`); + break; + } + console.log(btc_private_key); - // This response was sent by a backup (right direction) supernode - if(res_obj.params[0].db_inst==localbitcoinplusplus.wallets.my_local_flo_address) { - RM_RPC.receive_rpc_response.call( - this, - JSON.stringify(res_obj) - ); - return; - } + const withdraw_res = await _readDB("withdraw_btc", withdraw_id); + if(typeof withdraw_res=="object" + && typeof withdraw_res.utxo_addr=="object") { + const RM_WALLET = new localbitcoinplusplus.wallets; + let crypto_addr_gen = RM_WALLET.generateFloKeys(btc_private_key, withdraw_res.product); + let crypto_addr = crypto_addr_gen.address; - RM_RPC.backup_receive_rpc_response.call( - this, - JSON.stringify(res_obj) - ); + // Very Important Validation: to prevent different withdraw requests mashup + if(!Object.values(withdraw_res.utxo_addr).includes(crypto_addr)) { + console.warn(`${crypto_addr} deposit address not present in withdraw id ${withdraw_id}`); + break; + } + if(typeof localbitcoinplusplus.btc_private_key_array!=="object" + || Object.keys(localbitcoinplusplus.btc_private_key_array).length==0) { + localbitcoinplusplus.btc_private_key_array={}; + } + if(typeof localbitcoinplusplus.btc_private_key_array[withdraw_id] !== "object" + || localbitcoinplusplus.btc_private_key_array[withdraw_id]==null) { + localbitcoinplusplus.btc_private_key_array[withdraw_id] = []; + } + localbitcoinplusplus.btc_private_key_array[withdraw_id].push(btc_private_key); + + if(localbitcoinplusplus.btc_private_key_array[withdraw_id].length + ===Object.values(withdraw_res.utxo_addr).length) { + // When all the private keys are built successfully proceed further + res_obj.params[0].btc_private_key_array = + localbitcoinplusplus.btc_private_key_array[withdraw_id]; + + res_obj.params[0].trader_flo_address = withdraw_res.trader_flo_address; + + if(shamirs_shares_response.db_inst==localbitcoinplusplus.wallets.my_local_flo_address) { + RM_RPC.receive_rpc_response.call( + this, + JSON.stringify(res_obj) + ); - localbitcoinplusplus.actions.delay(300000).then(() => { - btc_pvt_arr[retrieve_pvtkey_req_id] = []; // Unset the object - }); + } else { + RM_RPC.backup_receive_rpc_response.call( + this, + JSON.stringify(res_obj) + ); + } + + if(!delete localbitcoinplusplus.btc_private_key_array[withdraw_id]) { + localbitcoinplusplus.btc_private_key_array[withdraw_id] = null; + } + + } } + btc_pvt_arr = Object.keys(btc_pvt_arr).filter(f=>f!==retrieve_pvtkey_req_id); } + } break; case "updateUserCryptoBalanceRequest": @@ -26415,7 +28616,7 @@ if (typeof backup_server_db_instance !== "object") { let backup_db_error_msg = `WARNING: Unknown DB instance. DB Backup failed.`; - showMessage(backup_db_error_msg); + console.trace(backup_db_error_msg); throw new Error(backup_db_error_msg); } @@ -26437,85 +28638,17 @@ updateUserDepositsResponseObject.updatedTraderDepositObject.id, true, false - ).then(()=>{ - if ( - localbitcoinplusplus.wallets.my_local_flo_address == - updateUserDepositsResponseObject.trader_flo_address - ) { - displayBalances( - updateUserDepositsResponseObject.trader_flo_address - ); - showMessage(`INFO: Your balance is updated.`); - } - return true; - }) + ) } else { - showMessage( - `WARNING: Failed to update balance in your DB. Please refresh.` + console.trace( + `WARNING: Failed to update balance in DB. Please refresh.` ); } }); } break; - case "updateUserBTCReservesRequest": - if ( - localbitcoinplusplus.master_configurations.supernodesPubKeys.includes( - res_obj.nodePubKey - ) - ) { - let updateUserReservesResponseObject = res_obj.params[0]; - let subjectuser = - res_obj.params[0].trader_flo_address || - res_obj.params[0].updatedReservesObject[0] - .trader_flo_address; - let backup_server_db_instance = ""; - if (typeof subjectuser != "string") return; - localbitcoinplusplus.kademlia - .determineClosestSupernode(subjectuser) - .then(my_closest_su_list => { - const primarySupernodeOfThisUser = my_closest_su_list[0].data.id; - backup_server_db_instance = - localbitcoinplusplus.newBackupDatabase.db[ - primarySupernodeOfThisUser - ]; - - if (typeof backup_server_db_instance !== "object") { - let backup_db_error_msg = `WARNING: Unknown DB instance. DB Backup failed.`; - showMessage(backup_db_error_msg); - throw new Error(backup_db_error_msg); - } - - let updateUserReservesResponseString = JSON.stringify( - updateUserReservesResponseObject.updatedReservesObject - ); - let updateUserReservesResponseStringHash = Crypto.SHA256( - updateUserReservesResponseString - ); - let isBalanceLegit = RM_WALLET.verify( - updateUserReservesResponseStringHash, - updateUserReservesResponseObject.updatedBTCReservesObjectSign, - res_obj.nodePubKey - ); - if (isBalanceLegit) { - backup_server_db_instance.backup_updateinDB( - "system_btc_reserves_private_keys", - updateUserReservesResponseObject - .updatedReservesObject[0], - true, - false - ); - return true; - } else { - showMessage( - `WARNING: Failed to update balance in your DB. Please refresh.` - ); - } - }); - } - break; - - case "sync_backup_supernode_from_backup_supernode_response": + case "sync_backup_supernode_from_backup_supernode_response": let su_db_data = res_obj.params[0]; if ( typeof localbitcoinplusplus.wallets.my_local_flo_address !== @@ -26530,6 +28663,10 @@ return; } + const timenow = + new Date(); + const lifetime = JSON.parse(localbitcoinplusplus.master_configurations.ordersLife); + const db_sync_promises = []; + if ( typeof res_obj.params == "object" && typeof res_obj.params[0] == "object" @@ -26575,6 +28712,9 @@ _updateinDB = foreign_db.backup_updateinDB.bind( foreign_db ); + _removeinDB = foreign_db.backup_removeinDB.bind( + foreign_db + ); } else { err_msg = `WARNING: Invalid Backup DB Instance Id: ${backup_db}.`; showMessage(err_msg); @@ -26585,9 +28725,6 @@ for (let tableStoreName in su_db_data) { i++; if (i == Object.keys(su_db_data).length - 2) { - localbitcoinplusplus.services[ - `can_serve_${su_db_data.trader_flo_address}` - ] = true; // Close unnecessary connections now reactor.dispatchEvent( "remove_extra_backup_connections" @@ -26606,17 +28743,60 @@ if (obj.length > 0) { for (var prop in obj) { if (!obj.hasOwnProperty(prop)) continue; - _updateinDB( + if(tableStoreName=="buyOrders" || tableStoreName=="sellOrders") { + if(timenow-obj[prop].timestamp>=lifetime.trade) { + db_sync_promises.push(_removeinDB(tableStoreName, obj[prop].id)); + continue; + } else { + db_sync_promises.push(localbitcoinplusplus.actions + .delay(timenow-obj[prop].timestamp) + .then(()=>_removeinDB(tableStoreName, obj[prop].id))) + } + } + + if(tableStoreName=="cash_deposits") { + if(timenow-obj[prop].timestamp>=lifetime.cashDeposit) { + db_sync_promises.push(_removeinDB(tableStoreName, obj[prop].id)); + continue; + } else { + db_sync_promises.push(localbitcoinplusplus.actions + .delay(timenow-obj[prop].timestamp) + .then(()=>_removeinDB(tableStoreName, obj[prop].id))) + } + } + + if(tableStoreName=="deposit") { + // if(timenow-obj[prop].timestamp>=lifetime.cryptoDeposit) { + // db_sync_promises.push(_removeinDB(tableStoreName, obj[prop].id)); + // continue; + // } else { + // db_sync_promises.push(localbitcoinplusplus.actions + // .delay(timenow-obj[prop].timestamp) + // .then(()=>_removeinDB(tableStoreName, obj[prop].id))) + // } + } + + if(tableStoreName=="withdraw_btc") { + if(timenow-obj[prop].timestamp>=lifetime.cryptoWithdraw) { + db_sync_promises.push(_removeinDB(tableStoreName, obj[prop].id)); + continue; + } else { + db_sync_promises.push(localbitcoinplusplus.actions + .delay(timenow-obj[prop].timestamp) + .then(()=>_removeinDB(tableStoreName, obj[prop].id))) + } + } + + db_sync_promises.push(_updateinDB( tableStoreName, obj[prop], obj[prop].id, true, false - ).then(() => { - showMessage( - `INFO: "${tableStoreName}" datastore syncing is complete.` - ); - }); + )); + showMessage( + `INFO: "${tableStoreName}" datastore syncing is complete.` + ); } } } catch (error) { @@ -26624,6 +28804,17 @@ } } })(); + await Promise.all(db_sync_promises); + + const RM_RPC = new localbitcoinplusplus.rpc(); + // Inform users + RM_RPC.send_rpc + .call(this, "supernode_message", { + trader_flo_address: + su_db_data.trader_flo_address, + server_msg: `Backup system is synced and ready to serve.` + }) + .then(server_response => doSend(server_response)); } break; @@ -26714,7 +28905,8 @@ const su_db_data_from_my_db = await localbitcoinplusplus.actions.get_sharable_db_data( tableArray, - backup_database + backup_database, + false ); const dbHashData_from_my_db = await localbitcoinplusplus.actions.getDBTablesLatestHashAndTimestamp( @@ -26764,7 +28956,7 @@ const mf = mismatched_fields[i]; latest_data[mf] = []; old_data[mf] = []; - const res_data_obj = await _readAllDB(mf, false); + const res_data_obj = await _readAllDB(mf); if(res_data_obj.length===0) { old_data[mf].push(res_data_obj); continue; @@ -26784,7 +28976,6 @@ )) { latest_data[mf].push(odho); } else { - if(typeof odho.is_deletable ==="boolean") continue; old_data[mf].push(odho); } } @@ -26839,96 +29030,6 @@ break; - case "validate_latest_db_hash": - if ( - localbitcoinplusplus.master_configurations.supernodesPubKeys.includes( - res_obj.nodePubKey - ) - ) { - const response_object = res_obj.params[0]; - if (typeof response_object.trader_flo_address != "string") - return; - - localbitcoinplusplus.kademlia - .determineClosestSupernode( - res_obj.params[0].trader_flo_address - ) - .then(my_closest_su_list => { - const primarySupernodeOfThisUser = - my_closest_su_list[0].data.id; - const backup_server_db_instance = - localbitcoinplusplus.newBackupDatabase.db[ - primarySupernodeOfThisUser - ]; - - if ( - typeof backup_server_db_instance !== "object" || - backup_server_db_instance == - localbitcoinplusplus.wallets.my_local_flo_address - ) { - let backup_db_error_msg = `WARNING: Unknown DB instance. DB Backup failed.`; - showMessage(backup_db_error_msg); - throw new Error(backup_db_error_msg); - } - - backup_server_db_instance - .backup_readDB("supernodesDbHash", response_object.id) - .then(my_db_hash_obj => { - if (typeof my_db_hash_obj == "object") { - if ( - my_db_hash_obj.vectorClock >= - response_object.vectorClock || - my_db_hash_obj.timestamp >= - response_object.timestamp - ) { - let diffs = []; // compare two objects and get the tables with difference in hash - - for (key in my_db_hash_obj) { - if (my_db_hash_obj.hasOwnProperty(key)) { - if ( - response_object[key] && - response_object[key] !== - my_db_hash_obj[key] && - ![ - "DBHash", - "data_of", - "id", - "timestamp", - "vectorClock" - ].includes(key) - ) { - diffs[key] = my_db_hash_obj[key]; - } - } - } - - localbitcoinplusplus.actions - .get_sharable_db_data( - diffs, - primarySupernodeOfThisUser - ) - .then(function(su_db_data) { - if (typeof su_db_data == "object") { - su_db_data.trader_flo_address = primarySupernodeOfThisUser; - su_db_data.receiver_flo_address = res_obj.globalParams.senderFloId; - RM_RPC.send_rpc - .call( - this, - "sync_backup_supernode_from_backup_supernode_response", - su_db_data - ) - .then(server_sync_response => - doSend(server_sync_response) - ); - } - }); - } - } - }); - }); - } - break; - case "store_backup_system_btc_reserves_private_keys": if ( typeof res_obj.params == "object" && @@ -27027,22 +29128,17 @@ ); } - if (typeof res_data.deposit_data == "object") - _updateinDB( - "deposit", - res_data.deposit_data, - res_data.deposit_data.id, - true, - false - ); - if (typeof res_data.btc_reserve_data == "object") - _updateinDB( - "system_btc_reserves_private_keys", - res_data.btc_reserve_data, - res_data.btc_reserve_data.id.id, - true, - false - ); + if (typeof res_data.deposit_data == "object") { + for (const deposits of res_data.deposit_data) { + _updateinDB( + "deposit", + deposits, + deposits.id, + true, + false + ); + } + } } } catch (e) { console.error(e); @@ -27081,13 +29177,11 @@ } if (typeof res_data.withdraw_btc_id == "string") _removeinDB("withdraw_btc", res_data.withdraw_btc_id); - if (typeof res_data.deposit_id == "string") - _removeinDB("deposit", res_data.deposit_id); - if (typeof res_data.btc_reserve_id == "string") - _removeinDB( - "system_btc_reserves_private_keys", - res_data.btc_reserve_id - ); + if(typeof res_data.deposit_id=="string") + _removeinDB("deposit", res_data.deposit_id); + if(typeof res_data.reserves_id=="string") + _removeinDB("system_btc_reserves_private_keys", + res_data.reserves_id); } } catch (e) { console.error(e); @@ -27117,7 +29211,7 @@ } break; - case "update_all_deposit_success": + case "update_all_cash_deposit_success": // If either Sender and Receiver are not Supernodes, return. if (!localbitcoinplusplus.master_configurations.supernodesPubKeys.includes( res_obj.nodePubKey) @@ -27190,68 +29284,14 @@ _updateinDB('withdraw_cash', successfull_withdraw_resp, successfull_withdraw_resp.id, true, false); - localbitcoinplusplus.actions.delay(24 * 60 * 60 * 1000).then(function() { + let withdraw_cash_life = JSON.parse(localbitcoinplusplus.master_configurations.ordersLife); + localbitcoinplusplus.actions.delay(withdraw_cash_life.cashWithdraw).then(function() { _removeinDB('withdraw_cash', successfull_withdraw_resp.id); }) }); } break; - - case "delete_deletables_from_supernode_db_instance": - if(localbitcoinplusplus.master_configurations.supernodesPubKeys - .includes(localbitcoinplusplus.wallets.my_local_flo_public_key) - && - localbitcoinplusplus.master_configurations.supernodesPubKeys - .includes(res_obj.nodePubKey)) { - - if(res_obj.params[0].delete_deletables===true - && typeof localbitcoinplusplus.newBackupDatabase - .db[res_obj.params[0].trader_flo_address]==="object") { - - const backup_db_inst = localbitcoinplusplus.newBackupDatabase - .db[res_obj.params[0].trader_flo_address]; - - const _readAllDB = backup_db_inst.backup_readAllDB.bind(backup_db_inst); - const _removeinDB = backup_db_inst.backup_removeinDB.bind(backup_db_inst); - - const tableArray = [ - "deposit", - "cash_deposits", - "withdraw_cash", - "withdraw_btc", - "cash_balances", - "crypto_balances", - "buyOrders", - "sellOrders", - "system_btc_reserves_private_keys", - "supernode_private_key_chunks" - ]; - - let del_promise = []; - - (async function() { - try { - for (let tbl of tableArray) { - const allDataPromises = await _readAllDB(tbl, false); - - for(t of allDataPromises) { - if(t.is_deletable===true) { - console.log(tbl, t); - del_promise.push(_removeinDB(tbl, t.id, true)); - } - } - } - - console.log(del_promise); - await Promise.all(del_promise); - } catch (error) { - throw new Error(error); - } - })(); - } - } - break; default: break; @@ -27306,6 +29346,7 @@ ); if (typeof res_obj.method !== "undefined") { + localbitcoinplusplus.CashierStatusObject[res_obj.nodePubKey].is_live=true; let response_from_sever; const RM_WALLET = new localbitcoinplusplus.wallets(); @@ -27336,6 +29377,9 @@ JSON.stringify(res_obj) ); break; + case "cashier_left": + localbitcoinplusplus.CashierStatusObject[res_obj.nodePubKey].is_live=false; + break; default: break; @@ -27551,6 +29595,7 @@ }; var db; + showPopup('main_loader', 'no'); const request = window.indexedDB.open(DBName, 2); request.onerror = function(event) { @@ -27801,15 +29846,18 @@ function signDBData(objectdata) { try { - if(!localbitcoinplusplus.master_configurations.supernodesPubKeys - .includes(localbitcoinplusplus.wallets.my_local_flo_public_key)) return objectdata; - + if(typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY !=="string") + throw new Error("Private key not found."); const RM_WALLET = new localbitcoinplusplus.wallets; + const pubKey = RM_WALLET.generateFloKeys(localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY).pubKeyHex; + if(!localbitcoinplusplus.master_configurations.supernodesPubKeys + .includes(pubKey)) return objectdata; + let objectdata_copy = JSON.parse(JSON.stringify(objectdata)); if(typeof objectdata_copy.db_sign=="string") delete objectdata_copy.db_sign; if(typeof objectdata_copy.db_signer=="string") delete objectdata_copy.db_signer; objectdata_copy.db_sign = RM_WALLET.sign(JSON.stringify(objectdata_copy), localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY); - objectdata_copy.db_signer = localbitcoinplusplus.wallets.my_local_flo_public_key; + objectdata_copy.db_signer = pubKey; return objectdata_copy; } catch (error) { throw new Error(error); @@ -27824,7 +29872,6 @@ let objectdata_copy = JSON.parse(JSON.stringify(objectdata)); delete objectdata_copy.db_sign; delete objectdata_copy.db_signer; - //return RM_WALLET.verify(JSON.stringify(objectdata_copy), objectdata.db_sign, objectdata.db_signer); if(RM_WALLET.verify(JSON.stringify(objectdata_copy), objectdata.db_sign, objectdata.db_signer)) { return true; } else { @@ -27939,7 +29986,7 @@ }) } - function readDB(tablename, id, filter_deletables = true) { + function readDB(tablename, id, with_dbsigns = true) { return new Promise((resolve, reject) => { var transaction = db.transaction([tablename]); var objectStore = transaction.objectStore(tablename); @@ -27954,12 +30001,13 @@ if(!exception_datastores.includes(tablename)) { if(!verifyDBData(request.result)) return resolve(); } - if (filter_deletables == true) { - if (typeof request.result.is_deletable == "undefined") { - resolve(request.result); - } else { - resolve(); + if (with_dbsigns == false) { + let eachrecordcopy = JSON.parse(JSON.stringify(request.result)); + if(typeof eachrecordcopy.db_sign=="string" || typeof eachrecordcopy.db_signer=="string") { + delete eachrecordcopy.db_sign; + delete eachrecordcopy.db_signer; } + resolve(eachrecordcopy); } else { resolve(request.result); } @@ -27975,7 +30023,7 @@ tablename, index, indexValue, - filter_deletables = true + with_dbsigns = true ) { return new Promise((resolve, reject) => { var transaction = db.transaction([tablename]); @@ -27991,22 +30039,19 @@ if (cursor.value[index] == indexValue) { if(!exception_datastores.includes(tablename)) { if(verifyDBData(cursor.value)) { - if (filter_deletables == true) { - if (typeof cursor.value.is_deletable == "undefined") { - response.push(cursor.value); + if (with_dbsigns == false) { + let eachrecordcopy = JSON.parse(JSON.stringify(cursor.value)); + if(typeof eachrecordcopy.db_sign=="string" || typeof eachrecordcopy.db_signer=="string") { + delete eachrecordcopy.db_sign; + delete eachrecordcopy.db_signer; } + response.push(eachrecordcopy); } else { response.push(cursor.value); } } } else { - if (filter_deletables == true) { - if (typeof cursor.value.is_deletable == "undefined") { - response.push(cursor.value); - } - } else { - response.push(cursor.value); - } + response.push(cursor.value); } } cursor.continue(); @@ -28017,45 +30062,35 @@ }); } - function readAllDB(tablename, filter_deletables = true, limit = 0) { + function readAllDB(tablename, with_dbsigns=true) { return new Promise((resolve, reject) => { let response = []; var objectStore = db.transaction(tablename).objectStore(tablename); - - // if ('getAll' in objectStore) { - // // IDBObjectStore.getAll() will return the full set of items in our store. - // objectStore.getAll().onsuccess = function(event) { - // resolve(event.target.result); - // }; - // } else { + objectStore.openCursor().onsuccess = function(event) { let cursor = event.target.result; if (cursor) { if(!exception_datastores.includes(tablename)) { if(verifyDBData(cursor.value)) { - if (filter_deletables == true) { - if (typeof cursor.value.is_deletable == "undefined") { - response.push(cursor.value); + if (with_dbsigns == false) { + let eachrecordcopy = JSON.parse(JSON.stringify(cursor.value)); + if(typeof eachrecordcopy.db_sign=="string" || typeof eachrecordcopy.db_signer=="string") { + delete eachrecordcopy.db_sign; + delete eachrecordcopy.db_signer; } + response.push(eachrecordcopy); } else { response.push(cursor.value); } } } else { - if (filter_deletables == true) { - if (typeof cursor.value.is_deletable == "undefined") { - response.push(cursor.value); - } - } else { - response.push(cursor.value); - } + response.push(cursor.value); } cursor.continue(); } else { resolve(response); } }; - // } }); } @@ -28090,8 +30125,6 @@ return new Error(error); } }); - - } function updateinDB( @@ -28109,62 +30142,84 @@ // leave the vector clock field unchanged } else { Obj.vectorClock += 1; - // If vectorClock is increased, also update timestamp - Obj.timestamp = +new Date(); } if (typeof Obj.timestamp !== "number") { Obj.timestamp = +new Date(); } var request = db.transaction([tablename], "readwrite") .objectStore(tablename); - if (updateByVectorClock === true) { - if (typeof key == "undefined") { - key = Obj[request.keyPath]; - } - let objectStoreRequest = request.get(key); - objectStoreRequest.onsuccess = function (event) { - var myRecord = objectStoreRequest.result; - if (typeof myRecord !== "object") { - Obj.vectorClock = - typeof Obj.vectorClock == "number" ? Obj.vectorClock : 0; + + if (typeof key == "undefined") { + key = Obj[request.keyPath]; + } + + let objectStoreRequest = request.get(key); + objectStoreRequest.onsuccess = function (event) { + var myRecord = objectStoreRequest.result; + if (myRecord==null + || myRecord== undefined + || typeof myRecord !== "object") { + Obj.vectorClock = + typeof Obj.vectorClock == "number" ? Obj.vectorClock : 0; + if(!exception_datastores.includes(tablename)) { + Obj = signDBData(Obj); + } + request = db.transaction([tablename], "readwrite") + .objectStore(tablename).put(Obj); + } else if(updateByVectorClock === true) { + + if (myRecord.vectorClock < Obj.vectorClock) { + // First verify data here if(!exception_datastores.includes(tablename)) { - Obj = signDBData(Obj); + if(verifyDBData(myRecord)===true) { + Obj = signDBData(Obj); + } else { + console.trace(myRecord); + return reject('Failed verification at db update'); + } } request = db.transaction([tablename], "readwrite") - .objectStore(tablename).put(Obj); - } else if (myRecord.vectorClock < Obj.vectorClock) { - if(!exception_datastores.includes(tablename)) { - Obj = signDBData(Obj); + .objectStore(tablename).put(Obj); + } else if (myRecord.vectorClock == Obj.vectorClock) { + if(myRecord.timestamp < Obj.timestamp) { + if(!exception_datastores.includes(tablename)) { + if(verifyDBData(myRecord)===true) { + Obj = signDBData(Obj); + } else { + console.trace(myRecord); + return reject('Failed verification at db update'); + } + } + request = db.transaction([tablename], "readwrite") + .objectStore(tablename).put(Obj); } - request = db.transaction([tablename], "readwrite") - .objectStore(tablename).put(Obj); } else { resolve(Obj); } - - request.onsuccess = function() { - resolve(Obj); + } else { + if(!exception_datastores.includes(tablename)) { + if(verifyDBData(myRecord)===true) { + if(typeof localbitcoinplusplus.wallets.my_local_flo_public_key=="string" + && localbitcoinplusplus.master_configurations.supernodesPubKeys + .includes(localbitcoinplusplus.wallets.my_local_flo_public_key)) { + Obj = signDBData(Obj); + } + } else { + return reject("Verification failed in updateinDB"); + } } - - request.onerror = function(e) { - reject(e); - } - }; - } else { - if(!exception_datastores.includes(tablename)) { - Obj = signDBData(Obj); + request = db.transaction([tablename], "readwrite") + .objectStore(tablename).put(Obj); + } + + request.onsuccess = function() { + resolve(Obj); } - request = db.transaction([tablename], "readwrite") - .objectStore(tablename).put(Obj); - } - - request.onsuccess = function() { - resolve(Obj); - } - request.onerror = function(e) { - reject(e); - } + request.onerror = function(e) { + reject(e); + } + }; } catch (error) { reject(error); return new Error(error); @@ -28589,7 +30644,7 @@ }.bind(this); }, - backup_readDB(tablename, id, filter_deletables = true) { + backup_readDB(tablename, id, with_dbsigns = true) { return new Promise((resolve, reject) => { this.transaction = this.db.transaction([tablename]); var objectStore = this.transaction.objectStore(tablename); @@ -28605,16 +30660,15 @@ if(!exception_datastores.includes(tablename)) { if(!verifyDBData(parent_request.result)) return resolve(); } - if (filter_deletables == true) { - if ( - typeof parent_request.result.is_deletable == "undefined" - ) { - resolve(parent_request.result); - } else { - resolve(); - } + if (with_dbsigns == false) { + let eachrecordcopy = JSON.parse(JSON.stringify(parent_request.result)); + if(typeof eachrecordcopy.db_sign=="string" || typeof eachrecordcopy.db_signer=="string") { + delete eachrecordcopy.db_sign; + delete eachrecordcopy.db_signer; + } + resolve(eachrecordcopy); } else { - resolve(parent_request.result); + resolve(parent_request.result); } } else { resolve(); @@ -28627,7 +30681,7 @@ tablename, index, indexValue, - filter_deletables = true + with_dbsigns = true ) { return new Promise((resolve, reject) => { this.transaction = this.db.transaction([tablename]); @@ -28644,22 +30698,19 @@ if(!exception_datastores.includes(tablename)) { if(verifyDBData(cursor.value)) { - if (filter_deletables == true) { - if (typeof cursor.value.is_deletable == "undefined") { - response.push(cursor.value); + if (with_dbsigns == false) { + let eachrecordcopy = JSON.parse(JSON.stringify(cursor.value)); + if(typeof eachrecordcopy.db_sign=="string" || typeof eachrecordcopy.db_signer=="string") { + delete eachrecordcopy.db_sign; + delete eachrecordcopy.db_signer; } + response.push(eachrecordcopy); } else { response.push(cursor.value); } } } else { - if (filter_deletables == true) { - if (typeof cursor.value.is_deletable == "undefined") { - response.push(cursor.value); - } - } else { - response.push(cursor.value); - } + response.push(cursor.value); } } @@ -28671,7 +30722,7 @@ }); }, - backup_readAllDB(tablename, filter_deletables = true) { + backup_readAllDB(tablename, with_dbsigns = true) { return new Promise((resolve, reject) => { let response = []; var objectStore = this.db @@ -28683,22 +30734,19 @@ if (cursor) { if(!exception_datastores.includes(tablename)) { if(verifyDBData(cursor.value)) { - if (filter_deletables == true) { - if (typeof cursor.value.is_deletable == "undefined") { - response.push(cursor.value); + if (with_dbsigns == false) { + let eachrecordcopy = JSON.parse(JSON.stringify(cursor.value)); + if(typeof eachrecordcopy.db_sign=="string" || typeof eachrecordcopy.db_signer=="string") { + delete eachrecordcopy.db_sign; + delete eachrecordcopy.db_signer; } + response.push(eachrecordcopy); } else { response.push(cursor.value); } } } else { - if (filter_deletables == true) { - if (typeof cursor.value.is_deletable == "undefined") { - response.push(cursor.value); - } - } else { - response.push(cursor.value); - } + response.push(cursor.value); } cursor.continue(); @@ -28758,23 +30806,22 @@ // leave the vector clock field unchanged } else { Obj.vectorClock += 1; - // If vectorClock is increased, also update timestamp - Obj.timestamp = +new Date(); } if (typeof Obj.timestamp !== "number") { Obj.timestamp = +new Date(); } this.request = this.db.transaction([tablename], "readwrite") .objectStore(tablename); + if (typeof key == "undefined") { + key = Obj[this.request.keyPath]; + } + let objectStoreRequest = this.request.get(key); - if (updateByVectorClock === true) { - if (typeof key == "undefined") { - key = Obj[this.request.keyPath]; - } - let objectStoreRequest = this.request.get(key); - objectStoreRequest.onsuccess = function(event) { - var myRecord = objectStoreRequest.result; - if (typeof myRecord !== "object") { + objectStoreRequest.onsuccess = function(event) { + var myRecord = objectStoreRequest.result; + if (myRecord==null + || myRecord== undefined + || typeof myRecord !== "object") { Obj.vectorClock = typeof Obj.vectorClock == "number" ? Obj.vectorClock : 0; if(!exception_datastores.includes(tablename)) { @@ -28782,44 +30829,57 @@ } this.request = this.db.transaction([tablename], "readwrite") .objectStore(tablename).put(Obj); - } else if (myRecord.vectorClock < Obj.vectorClock) { - // Don't sign rather verify data here + } else if (updateByVectorClock === true) { + if (myRecord.vectorClock < Obj.vectorClock) { + // First verify data here if(!exception_datastores.includes(tablename)) { - if(verifyDBData(Obj)===true) { - this.request = this.db.transaction([tablename], "readwrite") - .objectStore(tablename).put(Obj); + if(verifyDBData(myRecord)===true) { + Obj = signDBData(Obj); } else { - console.error('failed verification at backup update'); - console.trace(Obj); + console.trace(myRecord); + return reject('failed verification at backup update'); } } + this.request = this.db.transaction([tablename], "readwrite") + .objectStore(tablename).put(Obj); + } else if (myRecord.vectorClock == Obj.vectorClock) { + if(myRecord.timestamp < Obj.timestamp) { + if(!exception_datastores.includes(tablename)) { + if(verifyDBData(myRecord)===true) { + Obj = signDBData(Obj); + } else { + console.trace(myRecord); + return reject('Failed verification at backup db update'); + } + } + this.request = this.db.transaction([tablename], "readwrite") + .objectStore(tablename).put(Obj); + } } else { resolve(Obj); } - this.request.onsuccess = function() { - resolve(Obj); + } else { + if(!exception_datastores.includes(tablename)) { + if(verifyDBData(myRecord)===true) { + Obj = signDBData(Obj); + } else { + return reject("Verification failed in backup update"); + } } - - this.request.onerror = function(e) { - reject(e); - } - }.bind(this); - } else { - if(!exception_datastores.includes(tablename)) { - Obj = signDBData(Obj); + this.request = this.db.transaction([tablename], "readwrite") + .objectStore(tablename).put(Obj); + } + + this.request.onsuccess = function() { + resolve(Obj); } - this.request = this.db.transaction([tablename], "readwrite") - .objectStore(tablename).put(Obj); - } - this.request.onsuccess = function() { - resolve(Obj); - } - - this.request.onerror = function(e) { - reject(e); - } + this.request.onerror = function(e) { + reject(e); + } + }.bind(this); + } catch (error) { reject(error); return new Error(error); @@ -28947,7 +31007,7 @@ localbitcoinplusplus.master_configurations.tradableAsset1.map( asset => bitjslib(asset) ); - kickInit(); + await kickInit(); } ); } catch (error) { @@ -28969,9 +31029,7 @@ : `No FLO Id found`; showMessage(`Your FLO Id: ${my_flo_id}`); - const localbitcoinuserdiv = document.getElementById( - "localbitcoinuserdiv" - ); + const localbitcoinuserdiv = document.getElementById("localbitcoinuserdiv"); localbitcoinuserdiv.innerHTML = `${my_flo_id}`; // showMessage ->updating your balances @@ -29035,54 +31093,49 @@ // localbitcoinUser Database const dataBaseUIOperations = async function() { - localbitcoinplusplus.is_ui_loaded = true; - const RM_WALLET = new localbitcoinplusplus.wallets(); const RM_TRADE = new localbitcoinplusplus.trade(); const RM_RPC = new localbitcoinplusplus.rpc(); try { + localbitcoinplusplus.is_ui_loaded = true; readDB("localbitcoinUser", "00-01").then(async function(idbData) { + if(typeof localbitcoinplusplus.wallets.my_local_flo_address!=="string" + && localbitcoinplusplus.wallets.my_local_flo_address.length<=0) { + return false; + } + // Declare the user flo address - const MY_LOCAL_FLO_ADDRESS = (localbitcoinplusplus.wallets.my_local_flo_address = - idbData.myLocalFLOAddress); - const MY_LOCAL_FLO_PUBLIC_KEY = (localbitcoinplusplus.wallets.my_local_flo_public_key = - idbData.myLocalFLOPublicKey); - - // Get live trading prices - localbitcoinplusplus.actions.request_live_prices_from_server(); - - // Send request to others to link your flo id to your local ip - linkMyLocalIPToMyFloId(); - - // restore k-bucket - const dbObj = await localbitcoinplusplus.kademlia.restoreKbucket( - MY_LOCAL_FLO_ADDRESS, - localbitcoinplusplus.BASE_BLOCKCHAIN, - KBucket - ); + const MY_LOCAL_FLO_ADDRESS = localbitcoinplusplus.wallets.my_local_flo_address; + const MY_LOCAL_FLO_PUBLIC_KEY = localbitcoinplusplus.wallets.my_local_flo_public_key; // launch supernode kbucket if ( localbitcoinplusplus.master_configurations.supernodesPubKeys.includes( - idbData.myLocalFLOPublicKey + MY_LOCAL_FLO_PUBLIC_KEY ) ) { - // Build Supernodes KBuckets - launchSupernodesKBuckects = await localbitcoinplusplus.kademlia.launchSupernodesKBucket(); - // Request other supernodes KBucket data - // let requestSupernodeKBData = await localbitcoinplusplus.rpc.prototype - // .send_rpc - // .call(this, "requestSupernodesKBucketData", {}); - // doSend(requestSupernodeKBData); + reactor.dispatchEvent("remove_temp_data_from_db", localbitcoinplusplus.wallets.my_local_flo_address); + reactor.dispatchEvent("user_flo_keys_active", localbitcoinplusplus.wallets.my_local_flo_public_key); } // Send your id to Supernode kbucket if ( !localbitcoinplusplus.master_configurations.supernodesPubKeys.includes( - localbitcoinplusplus.wallets.my_local_flo_public_key + MY_LOCAL_FLO_PUBLIC_KEY ) ) { + if ( + typeof localbitcoinplusplus.MY_SUPERNODE_FLO_ADDRESS == "string" + ) { + idbData.lastConnectedTime = +new Date(); + idbData.lastConnectedSupernode = localbitcoinplusplus.MY_SUPERNODE_FLO_ADDRESS; + updateinDB("localbitcoinUser", idbData); + } else { + mss = `WARNING: Failed to update current supernode connected status in localbitcoinUser.`; + showMessage(mss); + throw new Error(mss); + } let kbuck = localbitcoinplusplus.kademlia.floIdToKbucketId( localbitcoinplusplus.BASE_BLOCKCHAIN, MY_LOCAL_FLO_ADDRESS @@ -29108,7 +31161,42 @@ doSend(addNewKNode); }); - } + + localbitcoinplusplus.actions.sync_with_supernode( + MY_LOCAL_FLO_ADDRESS + ); + + // Get live trading prices + localbitcoinplusplus.actions.request_live_prices_from_server(); + + // If connected with Backup Supernode, request it to sync data. + const closestSuList = await readAllDB("myClosestSupernodes"); + + const switchMyWS = new backupSupernodesWebSocketObject(); + const connectedWSServerFloId = await switchMyWS.getFloIdFromWSUrl( + websocket.url + ); + if (connectedWSServerFloId !== closestSuList[0].trader_flo_address) { + + const RM_RPC = new localbitcoinplusplus.rpc(); + let server_response = await RM_RPC.send_rpc.call( + this, + "nextBackupSupernodeToSyncDataBeforeActingAsBackupSupernodeNodeRequest", + { + trader_flo_address: MY_LOCAL_FLO_ADDRESS, + receiver_flo_address: connectedWSServerFloId + } + ); + doSend(server_response); + + showMessage(`INFO: Backup Supernode is collecting information about you. This could take some time. + You will be notified soon as soon as system is ready to serve you.`); + } + + } + + // Send request to others to link your flo id to your local ip + linkMyLocalIPToMyFloId(); readDB("userPublicData", MY_LOCAL_FLO_ADDRESS).then(function( pubic_data_response @@ -29131,33 +31219,17 @@ // update the user data from other su first //wsUri = await localbitcoinplusplus.kademlia.getSupernodeSeed(idbData.myLocalFLOAddress); - if ( - !localbitcoinplusplus.master_configurations.supernodesPubKeys.includes( - idbData.myLocalFLOAddress - ) - ) { - if ( - typeof localbitcoinplusplus.MY_SUPERNODE_FLO_ADDRESS == "string" - ) { - idbData.lastConnectedTime = +new Date(); - idbData.lastConnectedSupernode = - localbitcoinplusplus.MY_SUPERNODE_FLO_ADDRESS; - updateinDB("localbitcoinUser", idbData); - } else { - mss = `WARNING: Failed to update current supernode connected status in localbitcoinUser.`; - showMessage(mss); - throw new Error(mss); - } - } - // Show balances displayBalances(idbData.myLocalFLOAddress); /* Give user the facillity to trade */ buildTradeUI(idbData); - // Deposit / Withdraw asset - depositWithdrawAsset(idbData.myLocalFLOAddress); + // Deposit Cryptos + depositCrypto(idbData.myLocalFLOAddress); + + // Withdraw Crypto + withdrawCrypto(idbData.myLocalFLOAddress); // Deposit / Withdraw Fiat depositWithdrawFiat(idbData.myLocalFLOAddress); @@ -29168,9 +31240,6 @@ // Send Tx UI buildBroadcastTxUI(); - // Upload files to DB - uploadFileToDB(); - if ( localbitcoinplusplus.master_configurations.supernodesPubKeys.includes( MY_LOCAL_FLO_PUBLIC_KEY @@ -29194,40 +31263,15 @@ ); } - localbitcoinplusplus.actions.sync_with_supernode( - MY_LOCAL_FLO_ADDRESS + hidePopup(); // hide main_loader + + notify( + `Connection successfull. Welcome to Local Bitcoin Plus Plus P2P trading platform.` ); - showMessage( - `Connection successfull. Welcome to Local Bitcoin Plus Plus P2P trading platform.` - ); - - // If connected with Backup Supernode, request it to sync data. - const closestSuList = await readAllDB("myClosestSupernodes"); - - const switchMyWS = new backupSupernodesWebSocketObject(); - const connectedWSServerFloId = await switchMyWS.getFloIdFromWSUrl( - websocket.url - ); - if (connectedWSServerFloId!==closestSuList[0].trader_flo_address) { - - const RM_RPC = new localbitcoinplusplus.rpc(); - let server_response = await RM_RPC.send_rpc.call( - this, - "nextBackupSupernodeToSyncDataBeforeActingAsBackupSupernodeNodeRequest", - { - trader_flo_address: MY_LOCAL_FLO_ADDRESS, - receiver_flo_address: connectedWSServerFloId - } - ); - doSend(server_response); - - showMessage(`INFO: Backup Supernode is collecting information about you. This could take some time. - You will be notified soon as soon as system is ready to serve you.`); - } }); } catch (e) { - showMessage( + notify( "ERROR: Failed to initialise the localbitcoinUser database. You are unable to trade at the moment." ); throw new Error( @@ -29248,10 +31292,10 @@ typeof sellOrders == "object" ? Promise.resolve(sellOrders) : readDBbyIndex("sellOrders", "trader_flo_address", myFloId); - let my_trades_div = document.getElementById("my_trades_div"); + let my_trades_div = document.getElementById("orders_container"); + my_trades_div.innerHTML = ''; const RM_TRADE = new localbitcoinplusplus.trade(); - let t = `Your Trade Orders: `; - t += `