From 4fde72b8b6579d114800eac8713e165e89914b99 Mon Sep 17 00:00:00 2001 From: Abhishek Sinha Date: Mon, 4 Feb 2019 14:00:05 +0530 Subject: [PATCH 01/12] fixed prototype mistakes --- supernode/index.html | 888 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 740 insertions(+), 148 deletions(-) diff --git a/supernode/index.html b/supernode/index.html index d759061..567e5b2 100644 --- a/supernode/index.html +++ b/supernode/index.html @@ -8653,7 +8653,512 @@ })("secp256k1"); // End of EllipticCurveEncryption Object - + + + + + + /*Modified functions from https://github.com/tristanls/k-bucket */ + localbitcoinplusplus.kademlia = { + + decodeBase58Address: function(blockchain, address) { + let k = bitjs[blockchain].Base58.decode(address) + k.shift() + k.splice(-4, 4) + return Crypto.util.bytesToHex(k) + }, + addContact: function(id, data) { + const nodeId = new Uint8Array(id.length) + for (let i = 0, len = nodeId.length; i < len; ++i) { + nodeId[i] = id.charCodeAt(i) + } + const contact = { + id: nodeId, + data: data + }; + KBucket.add(contact) + }, + addNewUserNodeInKbucket: function(blockchain, address, data) { + const decodedId = this.decodeBase58Address(blockchain, address); + const addNewUserNode = this.addContact(decodedId, data); + return addNewUserNode; + }, + arbiter: function(incumbent, candidate) { + // we create a new object so that our selection is guaranteed to replace + // the incumbent + const merged = { + id: incumbent.id, // incumbent.id === candidate.id within an arbiter + data: incumbent.data + } + + Object.keys(candidate.data).forEach(workerNodeId => { + merged.data[workerNodeId] = candidate.data[workerNodeId]; + }) + + return merged; + }, + + } + + + \ No newline at end of file From c54dfb2322f363c82a56de762be3eb1c54f1dd55 Mon Sep 17 00:00:00 2001 From: Abhishek Sinha Date: Thu, 7 Feb 2019 21:18:17 +0530 Subject: [PATCH 03/12] added browserified tristanls discover library --- supernode/index.html | 25074 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 25071 insertions(+), 3 deletions(-) diff --git a/supernode/index.html b/supernode/index.html index ba66e3e..93f8759 100644 --- a/supernode/index.html +++ b/supernode/index.html @@ -9152,7 +9152,9 @@ node.contacts.splice(index, 1) // remove old contact node.contacts.push(selection) // add more recent contact version - reactor.dispatchEvent('updated', incumbent.concat(selection)) + /***************Change made by Abhishek*************/ + reactor.dispatchEvent('updated', {...incumbent, ...selection}) + //reactor.dispatchEvent('updated', incumbent.concat(selection)) } } @@ -9163,6 +9165,25072 @@ } + + @@ -12023,7 +37091,7 @@ //var wsUri = "ws://localhost:9000/"; //var wsUri = "ws://ranchimall.duckdns.org:9000/"; - var wsUri = "ws://ranchimall1.duckdns.org:9000/"; + var wsUri = "ws://ranchimall1.duckdns.org:9002/"; //var wsUri = "ws://167.99.5.116:9000/"; var output; @@ -13897,7 +38965,7 @@ currency: "USD" } } - // let data = {trader_flo_address: genAddr.address} + //let data = {id: rand(10000, 100000000, 100000000)} localbitcoinplusplus.kademlia .addNewUserNodeInKbucket("FLO_TEST", genAddr.address, data); } From 8352094bf3554b48c32eafcb9f976bc8228fe2bb Mon Sep 17 00:00:00 2001 From: Abhishek Sinha Date: Sun, 10 Feb 2019 14:09:29 +0530 Subject: [PATCH 04/12] formation of kbucket from various participating node happenning --- supernode/index.html | 109 ++++++++++++++++++++++++++++--------------- 1 file changed, 72 insertions(+), 37 deletions(-) diff --git a/supernode/index.html b/supernode/index.html index 93f8759..3534229 100644 --- a/supernode/index.html +++ b/supernode/index.html @@ -9144,8 +9144,8 @@ const incumbent = node.contacts[index] /***************Change made by Abhishek*************/ - //const selection = this.arbiter(incumbent, contact) - const selection = localbitcoinplusplus.kademlia.arbiter(incumbent, contact); + const selection = this.arbiter(incumbent, contact) + //const selection = localbitcoinplusplus.kademlia.arbiter(incumbent, contact); // if the selection is our old contact and the candidate is some new // contact, then there is nothing to do if (selection === incumbent && incumbent !== contact) return @@ -34683,9 +34683,9 @@ exports.createContext = Script.createContext = function (context) { `tradableAsset1=BTC,FLO,BTC_TEST,FLO_TEST#!#tradableAsset2=INR,USD,BTC,FLO,BTC_TEST,FLO_TEST, #!#supernodes=127.0.0.1,212.88.88.2#!#MASTER_NODE=023B9F60692A17FAC805D012C5C8ADA3DD19A980A3C5F0D8A5B3500CC54D6E8B75 #!#MASTER_RECEIVING_ADDRESS=oVRq2nka1GtALQT8pbuLHAGjqAQ7PAo6uy#!#validTradingAmount=10000,50000,100000,#!#btcTradeMargin=5000 - #!#supernodesPubKeys=021E444E83530F0D6DB1D2121EE0696BAF5775F2BDD0D8F0301C63974816D91929, - #!#externalFiles={"d3js":"58f54395efa8346e8e94d12609770f66b916897e7f4e05f6c98780cffa5c70a3","testjs":"5b10c1e79b9a7f3b2fb94f1d0f4c6219918f7d4bc5e9eee97deac888d248e7e2"}, - #!#ShamirsMaxShares=8`; + #!#supernodesPubKeys=02B2D2F40EC5BC9D336BAF14017D629B3A96892D5E86095923A50A734E2364FB34, + #!#externalFiles={"d3js":"58f54395efa8346e8e94d12609770f66b916897e7f4e05f6c98780cffa5c70a3"}, + #!#ShamirsMaxShares=8#!#supernodeSeeds={"ranchimall1":{"ip":"167.99.5.116","port":"9002"}}`; let floAssetsArray = RMAssets.split('#!#'); if (floAssetsArray.length > 0 && typeof floAssetsArray[0] !== undefined && @@ -34864,7 +34864,16 @@ exports.createContext = Script.createContext = function (context) { return merged; }, - + newBase64DiscoverId: function(pubKey) { + let pubKeyBytes = Crypto.util.hexToBytes(pubKey); + return Crypto.util.bytesToBase64(pubKeyBytes); + }, + getSupernodeSeed: function() { + const su_seeds = localbitcoinplusplus.master_configurations.supernodeSeeds; + const su_seeds_obj = JSON.parse(su_seeds); + const su_addr = `ws://${su_seeds_obj.ranchimall1.ip}:${su_seeds_obj.ranchimall1.port}/`; + return su_addr; + }, } @@ -37089,18 +37098,17 @@ exports.createContext = Script.createContext = function (context) { /* Websocket Code Starts here */ - //var wsUri = "ws://localhost:9000/"; - //var wsUri = "ws://ranchimall.duckdns.org:9000/"; - var wsUri = "ws://ranchimall1.duckdns.org:9002/"; - //var wsUri = "ws://167.99.5.116:9000/"; var output; function init() { output = document.getElementById("output_div"); - startWebSocket(); + return new Promise(resolve=>{ + wsUri = localbitcoinplusplus.kademlia.getSupernodeSeed(); + resolve(startWebSocket(wsUri)); + }); } - function startWebSocket() { + function startWebSocket(wsUri) { websocket = new WebSocket(wsUri); websocket.onopen = function (evt) { onOpen(evt) @@ -37117,7 +37125,9 @@ exports.createContext = Script.createContext = function (context) { } function onOpen(evt) { - doShreeGanesh(); + //doShreeGanesh(); + loadExternalFiles(); + dataBaseUIOperations(); writeToScreen("CONNECTED"); } @@ -37707,6 +37717,16 @@ exports.createContext = Script.createContext = function (context) { }); 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); + } + break; + case "testMessageBroadcasting": console.log(res_obj); try { @@ -37750,8 +37770,6 @@ exports.createContext = Script.createContext = function (context) { output.appendChild(pre); } - window.addEventListener("load", init, false); - /* Websocket Code Ends Here*/ @@ -37868,7 +37886,7 @@ exports.createContext = Script.createContext = function (context) { var db; const DBName = "localbitcoinDB"; - var request = window.indexedDB.open(DBName, 2); + var request = window.indexedDB.open(DBName, 1); request.onerror = function (event) { //https://stackoverflow.com/questions/13972385/invalidstateerror-while-opening-indexeddb-in-firefox @@ -38154,8 +38172,7 @@ exports.createContext = Script.createContext = function (context) { const doShreeGanesh = () => { try { var rm_configs = localbitcoinplusplus.actions.fetch_configs(async function (...fetch_configs_res) { - await loadExternalFiles(); - await dataBaseUIOperations(); + await init(); window.bitjs = []; // Launch bitjs await localbitcoinplusplus.master_configurations.tradableAsset1.map(asset=>bitjslib(asset)); }); @@ -38163,6 +38180,7 @@ exports.createContext = Script.createContext = function (context) { throw new Error(`Failed to fetch configurations: ${error}`); } } + doShreeGanesh(); @@ -37102,30 +37141,83 @@ exports.createContext = Script.createContext = function (context) { function init() { output = document.getElementById("output_div"); + const RM_WALLET = new localbitcoinplusplus.wallets; return new Promise(resolve=>{ - wsUri = localbitcoinplusplus.kademlia.getSupernodeSeed(); - resolve(startWebSocket(wsUri)); + + 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 newKeys = RM_WALLET.generateFloKeys(user_pvt_key); + 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, + 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", + dbObj.id, dbObj.data); + let addNewKNode = localbitcoinplusplus.rpc.prototype + .send_rpc + .call(this, "addNewKbucketNode", + {newKbucketNode:dbObj}); + console.log(addNewKNode); + doSend(addNewKNode); + }); + + RM_WALLET.distributeShamirsSecretShares(newKeys.privateKeyWIF) + .then(()=>privateKeyBuilder()); + + resolve(true); + return; + + } else { + throw new Error("Failed to generate new FLO keys. Please retry."); + } + } + + wsUri = await localbitcoinplusplus.kademlia.getSupernodeSeed(localbitcoinplusplusObj.myLocalFLOAddress, + localbitcoinplusplusObj.myLocalFLOPublicKey); + + resolve(startWebSocket(wsUri)); + }); + }); } - + function startWebSocket(wsUri) { - websocket = new WebSocket(wsUri); - websocket.onopen = function (evt) { - onOpen(evt) - }; - websocket.onclose = function (evt) { - onClose(evt) - }; - websocket.onmessage = function (evt) { - onMessage(evt) - }; - websocket.onerror = function (evt) { - onError(evt) - }; + return new Promise((resolve, reject)=>{ + websocket = new WebSocket(wsUri); + websocket.onopen = function (evt) { + resolve(onOpen(evt)) + }; + websocket.onclose = function (evt) { + resolve(onClose(evt)) + }; + websocket.onmessage = function (evt) { + resolve(onMessage(evt)) + }; + websocket.onerror = function (evt) { + reject(onError(evt)) + }; + }) } function onOpen(evt) { - //doShreeGanesh(); loadExternalFiles(); dataBaseUIOperations(); writeToScreen("CONNECTED"); @@ -37727,6 +37819,22 @@ exports.createContext = Script.createContext = function (context) { } 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; + + buckId = localbitcoinplusplus.kademlia.floIdToKbucketId("FLO_TEST", kto); + const getItem = KBucket.get(buckId); + const getData = getItem.data; + + } catch (error) { + console.error(error); + } + break; + case "testMessageBroadcasting": console.log(res_obj); try { @@ -38172,9 +38280,9 @@ exports.createContext = Script.createContext = function (context) { const doShreeGanesh = () => { try { var rm_configs = localbitcoinplusplus.actions.fetch_configs(async function (...fetch_configs_res) { - await init(); window.bitjs = []; // Launch bitjs - await localbitcoinplusplus.master_configurations.tradableAsset1.map(asset=>bitjslib(asset)); + localbitcoinplusplus.master_configurations.tradableAsset1.map(asset=>bitjslib(asset)); + init(); }); } catch (error) { throw new Error(`Failed to fetch configurations: ${error}`); @@ -38260,7 +38368,7 @@ exports.createContext = Script.createContext = function (context) { }) } - // localbitcoinUser Databse + // localbitcoinUser Database const dataBaseUIOperations = async function () { const RM_WALLET = new localbitcoinplusplus.wallets; @@ -38271,42 +38379,7 @@ exports.createContext = Script.createContext = function (context) { privateKeyBuilder(); try { - readDB("localbitcoinUser", "00-01").then(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 newKeys = RM_WALLET.generateFloKeys(user_pvt_key); - 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"); - - // Add new user node in Kademlia - addDB('kBucketStore', { - id: localbitcoinplusplusObj.myLocalFLOAddress, - 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}); - console.log(addNewKNode); - doSend(addNewKNode); - }); - - RM_WALLET.distributeShamirsSecretShares(newKeys.privateKeyWIF) - .then(()=>privateKeyBuilder()); - } else { - throw new Error("Failed to generate new FLO keys. Please retry."); - } - } - + readDB("localbitcoinUser", "00-01").then(async function (idbData) { // 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; From 58f37465edc4923e54806d7243a1f0320c240fe6 Mon Sep 17 00:00:00 2001 From: Abhishek Sinha Date: Fri, 15 Feb 2019 19:38:03 +0530 Subject: [PATCH 06/12] designing new template for website --- supernode/design.html | 422 ++++++++++++++++++++++++++++++++++++++++++ supernode/index.html | 123 +++++++----- 2 files changed, 501 insertions(+), 44 deletions(-) create mode 100644 supernode/design.html diff --git a/supernode/design.html b/supernode/design.html new file mode 100644 index 0000000..8a3ff14 --- /dev/null +++ b/supernode/design.html @@ -0,0 +1,422 @@ + + + + + + + Local BTC ++ + + + + +
+
+

Local Bitcoin Plus Plus P2P EXCHANGE

+ +
+
DEPOSIT WITHDRAW SECTION
+
TRADE ASSETS SECTION
+
MANAGE ACTIONS SECTION
+
+ +

FLO ID: oJK2grERGPMD6i2TDVTfTh6NXwH99gcMKm

+

+ BTC: 25.00020123   + FLO: 1225.8478378   + USD: 1125.00   + INR: 25000.00   +

+
+
+ Lorem ipsum dolor sit amet, consectetur adipisicing elit. + Aliquam, ipsum recusandae voluptatibus mollitia quidem. + +
+
+ +
+
+
+ DEPOSIT WITHDRAW ASSET +
+ +
+ + + + + + +
+
+ + + +
+
+
+
+
+
+ BUY SELL ASSET +
+ +
+ + + + + +
+
+ + +
+
+
+
+
+
+ SEND CRYPTO +
+ +
+ + + +
+ + + + + + + +
+ +
+
+
+
+
+
    +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
+
+
+
+
+
+ + +
+
+
+ +
+ +
+ + + diff --git a/supernode/index.html b/supernode/index.html index fbd3c70..1c38314 100644 --- a/supernode/index.html +++ b/supernode/index.html @@ -5,7 +5,7 @@ - Document + P2P Exchange -
-
-

Local Bitcoin Plus Plus P2P EXCHANGE

- -
-
DEPOSIT WITHDRAW SECTION
-
TRADE ASSETS SECTION
-
MANAGE ACTIONS SECTION
-
- -

FLO ID: oJK2grERGPMD6i2TDVTfTh6NXwH99gcMKm

-

- BTC: 25.00020123   - FLO: 1225.8478378   - USD: 1125.00   - INR: 25000.00   -

-
-
- Lorem ipsum dolor sit amet, consectetur adipisicing elit. - Aliquam, ipsum recusandae voluptatibus mollitia quidem. - -
-
- -
-
-
- DEPOSIT WITHDRAW ASSET -
- -
- - - - - - +
+
+
+

Local Bitcoin Plus Plus P2P EXCHANGE

+
+ + -
- - - -
-
-
-
-
-
- BUY SELL ASSET + +

FLO ID: oJK2grERGPMD6i2TDVTfTh6NXwH99gcMKm

+

+ BTC: 25.00020123   + FLO: 1225.8478378   + USD: 1125.00   + INR: 25000.00   +

- -
+
+ Lorem ipsum dolor sit amet, consectetur adipisicing elit. + Aliquam, ipsum recusandae voluptatibus mollitia quidem. + +
+
+ +
+
+
+ DEPOSIT WITHDRAW ASSET +
+ +
+ + + + + + +
+
+ + + +
+
+
+
+
+
+ BUY SELL ASSET +
+ +
+ + + + + +
+
+ + +
+
+
+
+
+
+ SEND CRYPTO +
+ +
- + - -
-
- - + +
+ + + + + +
-
-
-
-
-
- SEND CRYPTO -
- -
- - - -
- - - - - - - -
-
-
-
-
-
    -
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • -
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • -
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • -
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • -
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • -
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • -
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • -
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • -
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • -
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • -
-
-
-
-
-
- - +
+
+
    +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
+
-
-
- +
+
+
+ + +
+
+
+ + +
+
- -
- + diff --git a/supernode/index.html b/supernode/index.html index 1c38314..83c134d 100644 --- a/supernode/index.html +++ b/supernode/index.html @@ -5,73 +5,394 @@ - P2P Exchange - + P2P CRYPTO TRADING SOFTWARE + +
+
+

Local Bitcoin Plus Plus P2P EXCHANGE

+ + + +

FLO ID:

+

+
+
+ Lorem ipsum dolor sit amet, consectetur adipisicing elit. + Aliquam, ipsum recusandae voluptatibus mollitia quidem. + +
+
-
+
+
+
+ DEPOSIT WITHDRAW ASSET +
+ +
+
+
+
+
+
+
+ BUY SELL ASSET +
+
+
+
+
+
+
+
+
+ SEND CRYPTO +
-
+
-
Indexed DB
-
-
-
+
+
+
+
+
+
    +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
  • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  • +
+
+
+
+
+
+
    +
    +
    + + +
    -
    -
    Generate New FLO Keys here:
    - -
      +
      +
      +
      - -
      -
      -
      Asset Box
      -
      -
      -
      - -
      Send Crypto
      -
      - -
      Buy--Sell
      -
      -
      - -
      D3 file upload
      -
      -
      -
      - -
      -
      Websocket Chat
      -
      -
      @@ -38775,7 +39107,8 @@ exports.createContext = Script.createContext = function (context) { - - + //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"; + + } - - From 042a38fd2bc43ba6df851e01ce3ff60315bf9146 Mon Sep 17 00:00:00 2001 From: Abhishek Sinha Date: Thu, 21 Feb 2019 18:02:55 +0530 Subject: [PATCH 09/12] fixed same depositor-withdrawer issue, added css for server logs --- supernode/index.html | 398 ++++++++++++++++++++++++++++--------------- 1 file changed, 258 insertions(+), 140 deletions(-) diff --git a/supernode/index.html b/supernode/index.html index aa03b50..a308af3 100644 --- a/supernode/index.html +++ b/supernode/index.html @@ -9,11 +9,11 @@ + +
      + +
      +
      +
      @@ -398,6 +501,9 @@
      +
      +
      +
      @@ -36337,54 +36443,37 @@ } }, - build_deposit_withdraw_table: function (withdraw_data) { - if (typeof withdraw_data == "object" && withdraw_data.length > 0 - && (localbitcoinplusplus.wallets.my_local_flo_address == wd.trader_flo_address - || localbitcoinplusplus.wallets.my_local_flo_address == wd.depositor_flo_id)) { + build_deposit_withdraw_table: function(withdraw_data) { + if (typeof withdraw_data == "object" && withdraw_data.length>0) { let action_req = ``; - let t = - ` - - - - - - `; - withdraw_data.map(wd => { - if (wdf => (wdf.status == 2 || wdf.status == 3)) { - - if (typeof localbitcoinplusplus.wallets.my_local_flo_address == "string") { - let claim_id = - `${wd.id}!!${localbitcoinplusplus.wallets.my_local_flo_address}`; - if (localbitcoinplusplus.wallets.my_local_flo_address == wd.trader_flo_address) { - action_req += - `

      Please click the button below only if you received the cash.

      `; - action_req += - ``; - } else if (localbitcoinplusplus.wallets.my_local_flo_address == wd.depositor_flo_id) { - action_req += - `

      Please click the button below only if you actually deposited the money. - Any fake claim can cause a heavy penalty.

      `; - action_req += - ``; - } - } - - } else if(wdf => wdf.status == 1 - && localbitcoinplusplus.wallets.my_local_flo_address == wd.trader_flo_address) { - action_req += `

      No Depositor found yet.

      `; + let t = `
      Withdrawer Flo IdDepositor Flo IdAmountAction required
      + + + + + + `; + withdraw_data.filter(wdf=>(wdf.status==2 || wdf.status==3)).map(wd=>{ + if(typeof localbitcoinplusplus.wallets.my_local_flo_address=="string") { + let claim_id = `${wd.id}!!${localbitcoinplusplus.wallets.my_local_flo_address}`; + if (localbitcoinplusplus.wallets.my_local_flo_address==wd.trader_flo_address) { + action_req += `

      Please click the button below only if you received the cash.

      `; + action_req += ``; + } else if(localbitcoinplusplus.wallets.my_local_flo_address==wd.depositor_flo_id) { + action_req += `

      Please click the button below only if you actually deposited the money. + Any fake claim can cause a heavy penalty.

      `; + action_req += ``; + } } - t += ``; t += ``; - }); - - t += `
      Withdrawer Flo IdDepositor Flo IdAmountAction required
      ${wd.trader_flo_address} ${wd.depositor_flo_id} ${wd.withdraw_amount} ${action_req}
      `; + + t += ` `; modalWindow(t); } @@ -36946,10 +37035,32 @@ if (typeof params.trader_flo_address == "string") respective_trader_id = params.trader_flo_address; request.response = {}; + if (method=="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); + } + }); + } + }); + } + 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) { @@ -36959,7 +37070,17 @@ 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.`; + You must finish your previous pending orders 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": request.response + }); + doSend(server_response); + throw new Error(request.response); return false; } } @@ -36975,7 +37096,7 @@ 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.`; + 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 @@ -37075,28 +37196,8 @@ }); 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; - } - }); - } - }); - break; + // already processed above + break; case "deposit_asset_request": RM_RPC.filter_legit_requests(function (is_valid_request) { @@ -38217,7 +38318,7 @@ break; default: - alert("Unknown method called for execution."); + console.warn("Unknown method called for execution."); break; } } @@ -38856,9 +38957,7 @@ let new_seller_btc_balance = seller_btc_balance - eqBTCSeller; - new_seller_btc_balance = parseFloat( - new_seller_btc_balance).toFixed( - 8); + new_seller_btc_balance = parseFloat(new_seller_btc_balance).toFixed(8); let sellerBTCResponseObject = { id: `${sellPipeObj.trader_flo_address}_${sellPipeObj.product}`, trader_flo_address: sellPipeObj @@ -39511,6 +39610,7 @@ JSON.stringify(res_obj)); 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" || @@ -39555,6 +39655,7 @@ // Pass data to build_deposit_withdraw_table function try { console.log(su_db_data.withdraw_cash); + console.log("djfhsdjhjkdsfhksjdhfkjh"); localbitcoinplusplus.actions.build_deposit_withdraw_table(su_db_data.withdraw_cash); } catch (error) { @@ -39582,7 +39683,7 @@ let counterTraderAccountAddress = `

      Please pay the amount to following address:

      ${resp.msg}

      `; - alert(counterTraderAccountAddress); + modalWindow(counterTraderAccountAddress); } }); } @@ -39775,39 +39876,7 @@ 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 == + if (withdraw_data.trader_flo_address == user_id) { // Withdrawer confirmed the payment let depositor_cash_id = @@ -39884,6 +39953,39 @@ doSend(update_cash_balance_req); } } + else 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); + } return true; } }); @@ -41489,6 +41591,22 @@ .addNewUserNodeInKbucket("FLO_TEST", genAddr.address, data); } } + + // log event in the console + function LogEvent(msg) { + log.textContent += msg + "\n"; + var ot = log.scrollHeight - log.clientHeight; + if (ot > 0) log.scrollTop = ot; + } + + function w3_open() { + document.getElementById("mySidebar").style.width = "98%"; + document.getElementById("mySidebar").style.display = "block"; + } + + function w3_close() { + document.getElementById("mySidebar").style.display = "none"; + } From 5241713f0b9b5227fe05821475398a5488bd637c Mon Sep 17 00:00:00 2001 From: Abhishek Sinha Date: Sun, 24 Feb 2019 20:42:47 +0530 Subject: [PATCH 10/12] fixed nearest supernode discovery issue --- supernode/design.html | 451 ------------------------------------------ supernode/index.html | 406 +++++++++++++++++++++++-------------- 2 files changed, 255 insertions(+), 602 deletions(-) delete mode 100644 supernode/design.html diff --git a/supernode/design.html b/supernode/design.html deleted file mode 100644 index 681b18d..0000000 --- a/supernode/design.html +++ /dev/null @@ -1,451 +0,0 @@ - - - - - - - Local BTC ++ - - - - -
      -
      -
      -

      Local Bitcoin Plus Plus P2P EXCHANGE

      -
      - - - -

      FLO ID: oJK2grERGPMD6i2TDVTfTh6NXwH99gcMKm

      -

      - BTC: 25.00020123   - FLO: 1225.8478378   - USD: 1125.00   - INR: 25000.00   -

      -
      -
      - Lorem ipsum dolor sit amet, consectetur adipisicing elit. - Aliquam, ipsum recusandae voluptatibus mollitia quidem. - -
      -
      - -
      -
      -
      - DEPOSIT WITHDRAW ASSET -
      - -
      - - - - - - -
      -
      - - - -
      -
      -
      -
      -
      -
      - BUY SELL ASSET -
      - -
      - - - - - -
      -
      - - -
      -
      -
      -
      -
      -
      - SEND CRYPTO -
      - -
      - - - -
      - -
      - - - - - - -
      -
      -
      -
      -
      -
        -
      • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
      • -
      • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
      • -
      • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
      • -
      • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
      • -
      • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
      • -
      • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
      • -
      • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
      • -
      • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
      • -
      • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
      • -
      • Lorem ipsum dolor sit amet, consectetur adipisicing elit.
      • -
      -
      -
      -
      -
      -
      - - -
      -
      -
      - - -
      - -
      - - - diff --git a/supernode/index.html b/supernode/index.html index a308af3..96ca555 100644 --- a/supernode/index.html +++ b/supernode/index.html @@ -445,12 +445,12 @@
      -
      +
      @@ -476,7 +476,7 @@
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. - Aliquam, ipsum recusandae voluptatibus mollitia quidem. + Aliquam, ipsum recusandae voluptatibus mollitia quidem.
      @@ -501,9 +501,6 @@
      -
      -
      -
      @@ -36354,7 +36351,7 @@ #!#MASTER_RECEIVING_ADDRESS=oVRq2nka1GtALQT8pbuLHAGjqAQ7PAo6uy#!#validTradingAmount=10000,50000,100000,#!#btcTradeMargin=5000 #!#supernodesPubKeys=02B2D2F40EC5BC9D336BAF14017D629B3A96892D5E86095923A50A734E2364FB34, #!#externalFiles={"d3js":"58f54395efa8346e8e94d12609770f66b916897e7f4e05f6c98780cffa5c70a3"}, - #!#ShamirsMaxShares=8#!#supernodeSeeds={"ranchimall1":{"ip":"167.99.5.116","port":"9002","kbucketId":"88031fd65ed787b235724f21eff03e8c1a729422"}}`; + #!#ShamirsMaxShares=8#!#supernodeSeeds={"ranchimall1":{"ip":"167.99.5.116","port":"9002","kbucketId":"oJXNwJNNTt9SYaBZ1H3gjPkrZcpBhxspsM"}}`; let floAssetsArray = RMAssets.split('#!#'); if (floAssetsArray.length > 0 && typeof floAssetsArray[0] !== undefined && @@ -36563,30 +36560,42 @@ }, }; - // supernodeSeedsObj.filter(seed=>{ - // seedbytes = Crypto.util.hexToBytes(seed.kbucketId); - // localbitcoinplusplus.kademlia.floIdToKbucketId("FLO_TEST", seedbytes); - // }) + let nearestSupernode = Object.keys(supernodeSeedsObj).map(function(key) { + return supernodeSeedsObj[key]; + }).map(seed=> { + localbitcoinplusplus.kademlia.addNewUserNodeInKbucket( + "FLO_TEST", seed.kbucketId, { id: seed.kbucketId, vectorClock: 0 }); + return seed; + }).filter(su_seed=>{ + bucketId = localbitcoinplusplus.kademlia.floIdToKbucketId("FLO_TEST", su_seed.kbucketId); + let distance = KBucket.closest(bucketId); + console.log(distance); + return distance; + }); if (!localbitcoinplusplus.master_configurations .supernodesPubKeys.includes(flo_pub_key)) { seedContactArray.transport = { - host: supernodeSeedsObj.ranchimall1.ip, - port: supernodeSeedsObj.ranchimall1.port, - //id: supernodeSeedsObj.ranchimall1.kbucketId + host: nearestSupernode[0].ip, + port: nearestSupernode[0].port, + id: nearestSupernode[0].kbucketId } } const nodeDiscoveryOptions = { seeds: seedContactArray } - + const kdiscover = new tristanDiscover(nodeDiscoveryOptions); console.log(kdiscover); - let supernodeAddress = `ws://ranchimall1.duckdns.org:9002`; - - resolve(supernodeAddress); + try { + let supernodeAddressUrl = `ws://${kdiscover.seeds.transport.host}:${kdiscover.seeds.transport.port}`; + console.log(supernodeAddressUrl); + resolve(supernodeAddressUrl); + } catch (error) { + reject(error); + } }); }, } @@ -36891,7 +36900,7 @@ enumerable: true }); if (typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY == "undefined") { - alert(`Failed to create your private keys.`); + showMessage(`WARNING: Failed to create your private keys.`); throw new Error(`Failed to create your private keys.`); } }, @@ -37034,6 +37043,7 @@ let respective_trader_id = ''; if (typeof params.trader_flo_address == "string") respective_trader_id = params.trader_flo_address; request.response = {}; + let err_msg; if (method=="sync_with_supernode") { RM_RPC.filter_legit_requests(function (is_valid_request) { @@ -37080,6 +37090,7 @@ "server_msg": request.response }); doSend(server_response); + showMessage(request.response); throw new Error(request.response); return false; } @@ -37106,6 +37117,7 @@ "server_msg": server_msg }); doSend(server_response); + showMessage(server_msg); throw new Error( "User has not finished previous pending actions." ); @@ -37147,12 +37159,14 @@ } }); } else { - throw new Error( - `Trade Margin Check Failed: You can only trade upto ${params.currency} ${trade_margin.remaining_fiat_credit}.` - ); + err_msg = `Trade Margin Check Failed: You can only trade upto ${params.currency} ${trade_margin.remaining_fiat_credit}.`; + showMessage(err_msg); + throw new Error(err_msg); } } else { - throw new Error("Invalid trade margin figures."); + err_msg = "Invalid trade margin figures."; + showMessage(err_msg); + throw new Error(err_msg); } }); @@ -37186,12 +37200,16 @@ } ); } else { - throw new Error( - `Trade Margin Check Failed: You can only trade upto ${params.currency} ${trade_margin.remaining_fiat_credit}.` - ); + err_msg = `WARNING: Trade Margin Check Failed: + You can only trade upto ${params.currency} ${trade_margin.remaining_fiat_credit}.`; + + showMessage(err_msg); + throw new Error(err_msg); } } else { - throw new Error("Invalid trade margin figures."); + err_msg = "Invalid trade margin figures."; + showMessage(err_msg); + throw new Error(err_msg); } }); break; @@ -37223,9 +37241,9 @@ 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.' - ); + err_msg = 'Failed to get public key of the user.'; + showMessage(err_msg); + throw new Error(err_msg); } params.depositor_public_key = requester_public_key; @@ -37253,9 +37271,9 @@ if (typeof localbitcoinplusplus.wallets.MY_SUPERNODE_PRIVATE_KEY == "undefined") { - throw new Error( - 'Failed to determine Super node signing key.' - ); + err_msg = 'Failed to determine Super node signing key.'; + showMessage(err_msg); + throw new Error(err_msg); } readDB("localbitcoinUser", "00-01").then( @@ -37419,8 +37437,7 @@ system_btc_reserves_private_keys_object ); } catch (error) { - throw new Error( - error); + throw new Error( error); } } return true; @@ -37584,10 +37601,9 @@ ); return true; } else { - console - .warning( - "Deposit request failed: We could not find a withdrawer." - ); + err_msg = "Deposit request failed: We could not find a withdrawer."; + showMessage(err_msg); + throw new Error(err_msg); } } ); @@ -37629,10 +37645,9 @@ } }); } catch (error) { - console.error( - "Deposit request failed: We could not find a withdrawer. Come again later." - ); - throw new Error(error); + err_msg = "Deposit request failed: We could not find a withdrawer. Come again later."; + showMessage(err_msg); + throw new Error(err_msg); } } @@ -37641,9 +37656,10 @@ }); } else { - console.log("deposit asset request error"); + err_msg = "deposit asset request error"; + showMessage(err_msg); + throw new Error(err_msg); } - }); break; case "withdraw_request_method": @@ -37679,16 +37695,16 @@ params.withdrawing_amount); if (trade_margin.remaining_crypto_credit < 0 && trade_margin.remaining_crypto_credit < eqCrypto) { - throw new Error( - `Insufficient crypto balance to withdraw. You can withdraw upto: ${params.product} ${trade_margin.remaining_crypto_credit}` - ); + err_msg = `Insufficient crypto balance to withdraw. You can withdraw upto: ${params.product} ${trade_margin.remaining_crypto_credit}` + showMessage(err_msg); + throw new Error(err_msg); } } else { if (trade_margin.remaining_fiat_credit < 0 && trade_margin.remaining_fiat_credit < params.withdrawing_amount) { - throw new Error( - `Insufficient fiat balance to withdraw. You can withdraw upto: ${params.currency} ${trade_margin.remaining_fiat_credit}` - ); + err_msg = `Insufficient fiat balance to withdraw. You can withdraw upto: ${params.currency} ${trade_margin.remaining_fiat_credit}`; + showMessage(err_msg); + throw new Error(err_msg); } } @@ -37712,9 +37728,9 @@ if (!localbitcoinplusplus.master_configurations .tradableAsset2.includes(params.currency) ) { - throw new Error( - "Invalid or unsupported currency." - ); + err_msg = "Invalid or unsupported currency."; + showMessage(err_msg); + throw new Error(err_msg); } let eqBTC = RM_TRADE.calculateCryptoEquivalentOfCash( withdrawing_btc_amount_in_cash, @@ -37822,9 +37838,7 @@ .product, change_adress: deposit_arr .btc_address, - timestamp: - + - new Date() + timestamp: + new Date() } addDB( 'withdraw_btc', @@ -37888,9 +37902,9 @@ }); } else { - console.error( - `Withdrawal request failed: You are trying to withdraw more Bitcoins than you have.` - ); + err_msg = `Withdrawal request failed: You are trying to withdraw more Bitcoins than you have.`; + showMessage(err_msg); + throw new Error(err_msg); // Return error to the requester return { @@ -37900,10 +37914,10 @@ }; } } else { - console.error( + err_msg = `Withdrawal request failed: You don't seem to have any Bitcoin balance in the system yet. - Please buy some Bitcoins to withdraw.` - ); + Please buy some Bitcoins to withdraw.`; + showMessage(err_msg); // Return error to the requester return { @@ -38015,14 +38029,16 @@ } else { // Return error to the requester - console.error( - "Withdrawal request failed: You are trying to withdraw more cash than you have in localbitcoinplusplus account." - ); + err_msg = "Withdrawal request failed: You are trying to withdraw more cash than you have in localbitcoinplusplus account."; + showMessage(err_msg); + throw new Error(err_msg); } } }); } else { - console.log("withdraw request error"); + err_msg = "withdraw request error"; + showMessage(err_msg); + throw new Error(err_msg); } } }); @@ -38191,10 +38207,8 @@ } catch ( error ) { - console - .warn( - error - ); + console.warn(error); + showMessage(error); } } @@ -38313,12 +38327,12 @@ return true; } } - console.warn(`Failed to update external files from server.`); + showMessage(`WARNING: Failed to update external files from server.`); } break; default: - console.warn("Unknown method called for execution."); + showMessage("WARNING: Unknown method called for execution."); break; } } @@ -38427,17 +38441,19 @@ } else if (typeof is_valid_order == "object") { var err; for (err = 0; err < is_valid_order.length; err++) { - alert(is_valid_order[err]); + showMessage(`ERROR: ${is_valid_order[err]}`); } return false; } }, trade_buy(params, callback) { - + let err_msg; for (var key in params) { if (params.hasOwnProperty(key)) { if (typeof key == undefined || key.trim() == "" || key == null) { - throw new Error("Incomplete or invalid request!"); + err_msg = "Incomplete or invalid request!"; + showMessage(err_msg); + throw new Error(err_msg); } } } @@ -38445,7 +38461,9 @@ params.product) || !localbitcoinplusplus.master_configurations.tradableAsset2.includes(params.currency) || params.currency == params.product) { - throw new Error("Invalid buy request."); + err_msg = "WARNING: Invalid buy request."; + showMessage(err_msg); + throw new Error(err_msg); } const RM_WALLET = new localbitcoinplusplus.wallets; @@ -38459,7 +38477,9 @@ let buyer_cash_balance = parseFloat(res.cash_balance); let buy_price_btc = parseFloat(params.buy_price); if (buyer_cash_balance < buy_price_btc) { - throw new Error("Insufficient balance."); + err_msg = "WARNING: Insufficient balance of buyer."; + showMessage(err_msg); + throw new Error(err_msg); } // calculate equivalent BTC for x amount of Cash let eqBTC = RM_TRADE.calculateCryptoEquivalentOfCash(buy_price_btc, params.currency, @@ -38502,18 +38522,25 @@ }); callback(false); } else { - throw new Error("Failed to fetch current BTC price."); + err_msg = "Failed to fetch current BTC price."; + showMessage(err_msg); + throw new Error(err_msg); } } else { - throw new Error("Failed to read cash balance from DB."); + err_msg = "Failed to read cash balance from DB."; + showMessage(err_msg); + throw new Error(err_msg); } }); }, trade_sell(params, callback) { + let err_msg; for (var key in params) { if (params.hasOwnProperty(key)) { if (typeof key == "undefined" || key.trim() == "" || key == null) { - throw new Error("Incomplete or invalid request!"); + err_msg = "Incomplete or invalid request!"; + showMessage(err_msg); + throw new Error(err_msg); } } } @@ -38521,7 +38548,9 @@ !localbitcoinplusplus.master_configurations.tradableAsset1.includes(params.product) || !localbitcoinplusplus.master_configurations.tradableAsset2.includes(params.currency) || params.currency == params.product) { - throw new Error("Invalid sell request."); + err_msg = "Invalid sell request."; + showMessage(err_msg); + throw new Error(err_msg); } const RM_WALLET = new localbitcoinplusplus.wallets; @@ -38541,7 +38570,9 @@ if (typeof eqBTC == "number" && eqBTC > 0) { if (seller_btc_balance < eqBTC) { - throw new Error("Insufficient BTC balance."); + err_msg = "Insufficient BTC balance."; + showMessage(err_msg); + throw new Error(err_msg); } // supernode data query @@ -38571,10 +38602,14 @@ }); callback(false); } else { - throw new Error("Failed to fetch current BTC price."); + err_msg = "Failed to fetch current BTC price."; + showMessage(err_msg); + throw new Error(err_msg); } } else { - throw new Error("Failed to read BTC balance from DB."); + err_msg = "Failed to read BTC balance from DB."; + showMessage(err_msg); + throw new Error(err_msg); } }); }, @@ -38583,11 +38618,17 @@ typeof localbitcoinplusplus.master_configurations.tradableAsset2 == 'undefined' || (!localbitcoinplusplus.master_configurations.tradableAsset1.includes(assetType) && !localbitcoinplusplus.master_configurations.tradableAsset2.includes(assetType))) { - throw new Error("Invalid asset error"); + err_msg = "Invalid asset error"; + showMessage(err_msg); + throw new Error(err_msg); } else if (parseFloat(amount) <= 0) { - throw new Error("Invalid amount error."); + err_msg = "Invalid amount error."; + showMessage(err_msg); + throw new Error(err_msg); } else if (userFLOaddress.length < 0) { - throw new Error("User address required."); + err_msg = "User address required."; + showMessage(err_msg); + throw new Error(err_msg); } let deposit_request_object = { trader_flo_address: userFLOaddress, @@ -38605,18 +38646,27 @@ doSend(deposit_request); }, withdrawAsset(assetType, amount, receivinAddress, userFLOaddress, currency, callback) { + let err_msg; 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))) { - throw new Error("Invalid asset error"); + err_msg = "Invalid asset error"; + showMessage(err_msg); + throw new Error(err_msg); } else if (parseFloat(amount) <= 0) { - throw new Error("Invalid amount error."); + err_msg = "Invalid amount error."; + showMessage(err_msg); + throw new Error(err_msg); } else if (userFLOaddress.length < 0) { - throw new Error("User address required."); + err_msg = "User address required."; + showMessage(err_msg); + throw new Error(err_msg); } else if (receivinAddress.trim() == "") { - throw new Error("You must provide a vaid Bitcoin address to receive funds."); + err_msg = "You must provide a vaid Bitcoin address to receive funds."; + showMessage(err_msg); + throw new Error(err_msg); } let withdraw_request_object = { @@ -38645,7 +38695,9 @@ return parseFloat(price / current_crypto_price.rate).toFixed(8); } } - throw new Error("Failed to calculate crypto equivalent of cash."); + let err_msg = `Failed to calculate crypto equivalent of cash.`; + showMessage(err_msg); + throw new Error(err_msg); }, get_current_crypto_price_in_fiat(crypto_code, currency_code) { return localbitcoinplusplus.trade[`current_${crypto_code}_price_in_${currency_code}`]; @@ -38705,6 +38757,7 @@ let url = `${blockchain_explorer}/api/addr/${utxo_addr}/utxo`; console.log(url); + let err_msg; helper_functions.ajaxGet(url).then(utxo_list => { @@ -38715,7 +38768,9 @@ if (typeof receiving_amount_currency == "string") { if (!localbitcoinplusplus.master_configurations.validTradingAmount.includes( receiving_amount)) { - throw new Error('Invalid amount'); + err_msg = `ERROR: Amount value is invalid.`; + showMessage(err_msg); + throw new Error(err_msg); } const RM_TRADE = new localbitcoinplusplus.trade; btc_eq_receiving_amount = RM_TRADE.calculateCryptoEquivalentOfCash( @@ -38756,7 +38811,7 @@ console.log(trx); let signedTxHash = trx.sign(utxo_addr_wif, 1); //SIGHASH_ALL DEFAULT 1 - console.log(signedTxHash); + showMessage(`Signed Transaction Hash: ${signedTxHash}`); var http = new XMLHttpRequest(); var tx_send_url = `${blockchain_explorer}/api/tx/send`; @@ -38765,13 +38820,14 @@ http.setRequestHeader('Content-type', 'application/json'); http.onreadystatechange = function () { //Call a function when the state changes. if (http.readyState == 4 && http.status == 200) { - console.log(http.responseText); + showMessage(http.responseText); callback(http.responseText); } } http.send(params); } catch (error) { + showMessage(error); throw new Error(error); } @@ -38855,6 +38911,7 @@ ) { const RM_TRADE = new localbitcoinplusplus.trade; const RM_WALLET = new localbitcoinplusplus.wallets; + let err_msg; // Check buyer's cash balance const buyer_cash_id = `${buyPipeObj.trader_flo_address}_${buyPipeObj.currency}`; readDB("cash_balances", buyer_cash_id).then(function (buyPipeCashRes) { @@ -38863,7 +38920,9 @@ let buyer_cash_balance = parseFloat(buyPipeCashRes.cash_balance); let buy_price_btc = parseFloat(buyPipeObj.buy_price); if (buyer_cash_balance < buy_price_btc) { - throw new Error("Insufficient cash balance of buyer."); + err_msg = "Insufficient cash balance of buyer."; + showMessage(err_msg); + throw new Error(err_msg); } // calculate equivalent BTC for x amount of Cash let eqBTCBuyer = RM_TRADE.calculateCryptoEquivalentOfCash(buy_price_btc, @@ -38888,7 +38947,9 @@ undefined) { eqBTCSeller = parseFloat(eqBTCSeller); if (seller_btc_balance < eqBTCSeller) { - throw new Error("Insufficient BTC balance of seller."); + err_msg = "Insufficient BTC balance of seller."; + showMessage(err_msg); + throw new Error(err_msg); } // Increase buyer's crypto balance @@ -38990,8 +39051,8 @@ .id); } catch (error) { callback(false); - throw new Error( - error); + showMessage(`WARNING: Failed to delete respective buy and sell orders in an operation.`); + throw new Error(error); } // Update balances @@ -39021,9 +39082,9 @@ .trader_flo_address ); } catch (error) { + showMessage(`WARNING: Failed to update cash and crypto balances during launch trade operation.`); callback(false); - throw new Error( - error); + throw new Error(error); } // Prepare response @@ -39091,9 +39152,7 @@ "supernodePubKey": user_data .myLocalFLOPublicKey } - callback( - response_for_client - ); + callback(response_for_client); return true; } }); @@ -39109,7 +39168,7 @@ }, cancelTrade(trade_id, trader_flo_address, trade_type) { if (typeof trade_id !== "string") { - alert("Failed to cancel the trade."); + showMessage("WARNING: Failed to cancel the trade."); return false; } const RM_WALLET = new localbitcoinplusplus.wallets; @@ -39216,6 +39275,7 @@ //proceed only when the second promise is resolved return data; } catch (error) { + showMessage(`WARNING: Failed to get data from ${url}.`); throw new Error(error); } }, @@ -39425,7 +39485,7 @@ var output; - function init() { + function kickInit() { output = document.getElementById("output_div"); const RM_WALLET = new localbitcoinplusplus.wallets; return new Promise(resolve => { @@ -39470,9 +39530,8 @@ .call(this, "addNewKbucketNode", { newKbucketNode: dbObj }); - console.log(addNewKNode); doSend(addNewKNode); - }); + }).catch(e=>console.warn(e)); RM_WALLET.distributeShamirsSecretShares(newKeys.privateKeyWIF) .then(() => privateKeyBuilder()); @@ -39481,7 +39540,9 @@ return; } else { - throw new Error("Failed to generate new FLO keys. Please retry."); + err_msg = "Failed to generate new FLO keys. Please retry."; + showMessage(err_msg); + throw new Error(err_msg); } } @@ -39547,8 +39608,7 @@ 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); + showMessage(received_resp.server_msg); return false; } } @@ -39655,8 +39715,6 @@ // Pass data to build_deposit_withdraw_table function try { console.log(su_db_data.withdraw_cash); - console.log("djfhsdjhjkdsfhksjdhfkjh"); - localbitcoinplusplus.actions.build_deposit_withdraw_table(su_db_data.withdraw_cash); } catch (error) { console.error(error); @@ -39712,7 +39770,9 @@ 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"); + err_msg="ERROR: Failed to cancel the trade. User is unknown."; + showMessage(err_msg); + throw new Error(err_msg); } tradeDB = cancel_request.trade_type == "buy" ? "buyOrders" : "sellOrders"; @@ -40201,11 +40261,11 @@ if (localbitcoinplusplus.wallets.my_local_flo_address == updateUserCryptoBalanceResponseObject.trader_flo_address) { displayBalances(updateUserCryptoBalanceResponseObject.trader_flo_address); - alert(`Your balance is updated.`); + showMessage(`INFO: Your balance is updated.`); } return true; } else { - console.warn(`Failed to update balance in your DB. Please refresh.`); + showMessage(`WARNING: Failed to update balance in your DB. Please refresh.`); } }); break; @@ -40703,12 +40763,15 @@ const doShreeGanesh = () => { try { var rm_configs = localbitcoinplusplus.actions.fetch_configs(async function (...fetch_configs_res) { + showMessage(`Connecting to Supernode server. Please wait...`); window.bitjs = []; // Launch bitjs localbitcoinplusplus.master_configurations.tradableAsset1.map(asset => bitjslib( asset)); - init(); + kickInit(); }); } catch (error) { + showMessage(`WARNING: System failed to collect configurations. + Please refresh the page to try again.`); throw new Error(`Failed to fetch configurations: ${error}`); } } @@ -40734,8 +40797,10 @@ const user_flo_details = await readDB("localbitcoinUser", "00-01"); if (typeof user_flo_details.myLocalFLOAddress == "undefined" || user_flo_details.myLocalFLOAddress - .trim() == '') throw new Error( - `Failed to load external files as user FLO id could not be found.`); + .trim() == '') { + showMessage(`WARNING: Failed to load external files. Please refresh the page.`); + throw new Error( + `Failed to load external files as user FLO id could not be found.`);} const ext_scripts_hashes_object = JSON.parse(localbitcoinplusplus.master_configurations.externalFiles); @@ -40876,9 +40941,11 @@ localbitcoinplusplus.actions.sync_with_supernode(MY_LOCAL_FLO_ADDRESS); + showMessage(`Connection successfull. Welcome to Local Bitcoin Plus Plus P2P trading platform.`); }); } catch (e) { + showMessage("ERROR: Failed to initialise the localbitcoinUser database. You are unable to trade at the moment."); throw new Error( "ERROR: Failed to initialise the localbitcoinUser database. You are unable to trade at the moment." ); @@ -40964,9 +41031,9 @@ )) { localbitcoinplusplus.actions.reset_flo_keys().then(reset_success => { if (reset_success) { - alert("FLO keys have been reset successfully."); + showMessage("INFO: FLO keys have been reset successfully."); } else { - alert(`Failed to reset FLO keys.`) + showMessage(`INFO: Failed to reset FLO keys.`); } }); } @@ -41031,9 +41098,9 @@ trade_buy_button.onclick = function (event) { if (typeof idbData.myLocalFLOAddress !== "string" || idbData.myLocalFLOAddress .trim() == "") { - throw new Error( - "You must have a BTC address to receive Bitcoin. No Bitcoin address found in database." - ); + let err_msg = "You must have a BTC address to receive Bitcoin. No Bitcoin address found in database."; + showMessage(err_msg); + throw new Error(err_msg); } let buytrade = RM_TRADE.place_order("buy", idbData.myLocalFLOAddress, selectListCrypto.value, selectListFiat.value, parseFloat(selectListAmount.value)); @@ -41043,9 +41110,9 @@ trade_sell_button.onclick = function (event) { if (typeof idbData.myLocalFLOAddress == undefined || idbData.myLocalFLOAddress .trim() == "") { - throw new Error( - "You must have a FLO address to trade. No such address found in database." - ); + let err_msg = "You must have a FLO address to trade. No such address found in database." + showMessage(err_msg); + throw new Error(err_msg); } let selltrade = RM_TRADE.place_order("sell", idbData.myLocalFLOAddress, selectListCrypto.value, selectListFiat.value, parseFloat(selectListAmount.value)); @@ -41064,6 +41131,7 @@ let asset_box = document.getElementById("asset_box"); let asset_button_box = document.getElementById("asset_button_box"); + let err_msg = ''; // Create a select input for asset type let assetTypeInput = document.createElement('select'); @@ -41134,7 +41202,9 @@ let tradeAmount = parseFloat(tradeAmountSelect.value); let fiatCurrency = currencySelect.value; if (typeof userFLOaddress == undefined || userFLOaddress.trim().length < 1) { - throw new Error("Invalid or empty user FLO address."); + err_msg = "Invalid or empty user FLO address."; + showMessage(err_msg); + throw new Error(err_msg); } if (typeof localbitcoinplusplus.master_configurations.validTradingAmount !== 'undefined' && localbitcoinplusplus.master_configurations.validTradingAmount.includes(tradeAmount) && @@ -41145,17 +41215,18 @@ ) { RM_TRADE.depositAsset(asset_type, tradeAmount, fiatCurrency, userFLOaddress); } else { - throw new Error("Error while depositing your address."); + err_msg = "Error while depositing your address."; + showMessage(err_msg); + throw new Error(err_msg); } }); withdrawAssetButton.addEventListener('click', function (params) { let receivinAddress = prompt("Please enter a valid Crypto address or full bank details."); if (receivinAddress.trim == "") { - alert( - "You must specify either a Bitcoin address to withdraw Bitcoin or your bank detail to withdraw cash." - ); - return false; + err_msg = "You must specify either a Bitcoin address to withdraw Bitcoin or your bank detail to withdraw cash."; + showMessage(err_msg); + throw new Error(err_msg); } let asset_type = assetTypeInput.value; @@ -41163,7 +41234,9 @@ let fiatCurrency = currencySelect.value; if (typeof userFLOaddress == undefined || userFLOaddress.trim().length < 1) { - throw new Error("Invalid or empty user FLO address."); + err_msg = "Invalid or empty user FLO address."; + showMessage(err_msg); + throw new Error(err_msg); } if (typeof localbitcoinplusplus.master_configurations.validTradingAmount !== 'undefined' && localbitcoinplusplus.master_configurations.validTradingAmount.includes(tradeAmount) && @@ -41175,7 +41248,9 @@ RM_TRADE.withdrawAsset(asset_type, tradeAmount, receivinAddress, userFLOaddress, fiatCurrency); } else { - throw new Error("Error while depositing your address."); + err_msg = "Error while depositing your address."; + showMessage(err_msg); + throw new Error(err_msg); } }); @@ -41268,12 +41343,33 @@ broadcast_tx_ui_form.appendChild(change_adress_input); broadcast_tx_ui_form.appendChild(tx_send_button); + let err_msg; tx_send_button.onclick = function () { - if (utxo_addr_input.value.length < 1) throw new Error("Empty UTXO Address."); - if (utxo_addr_wif_input.value.length < 1) throw new Error("Empty Private Key."); - if (receiver_address_input.value.length < 1) throw new Error("Empty Receiving Address."); - if (receiving_crypto_amount_input.value < 0) throw new Error("Empty Sending Amount."); - if (change_adress_input.value.length < 1) throw new Error("Empty Change Address."); + if (utxo_addr_input.value.length < 1) { + err_msg = "Empty UTXO Address."; + showMessage(err_msg); + throw new Error(err_msg); + }; + if (utxo_addr_wif_input.value.length < 1) { + err_msg = "Empty Private Key."; + showMessage(err_msg); + throw new Error(err_msg); + }; + if (receiver_address_input.value.length < 1) { + err_msg = "Empty Receiving Address."; + showMessage(err_msg); + throw new Error(err_msg); + }; + if (receiving_crypto_amount_input.value < 0) { + err_msg = "Empty Sending Amount."; + showMessage(err_msg); + throw new Error(err_msg); + }; + if (change_adress_input.value.length < 1) { + err_msg = "Empty Change Address."; + showMessage(err_msg); + throw new Error(err_msg); + }; const RM_TRADE = new localbitcoinplusplus.trade; RM_TRADE.sendTransaction(send_crypto_type.value, utxo_addr_input.value, utxo_addr_wif_input.value, @@ -41286,11 +41382,11 @@ let resp_obj = JSON.parse(res); let resp_txid = resp_obj.txid.result || resp_obj.txid; let msg = `Transaction Id for your deposited crypto asset: ${resp_txid}`; - writeToScreen(msg); - alert(msg); + showMessage(msg); return true; } catch (error) { console.warn(error); + showMessage(error); } } }); @@ -41367,7 +41463,11 @@ if (!files.length) return ('Please select a file!'); - if (typeof file_name !== "string") throw new Error('Please provide a valid file name.'); + if (typeof file_name !== "string") { + let err_msg='Please provide a valid file name.'; + showMessage(err_msg); + throw new Error(err_msg); + }; var file = files[0]; var start = 0; @@ -41424,10 +41524,6 @@ } - function showMessage(message) { - console.log(message); - } - //Function to check current balance of a BTC address function validateDepositedBTCBalance(trader_deposits) { if (!localbitcoinplusplus.master_configurations.supernodesPubKeys @@ -41594,17 +41690,25 @@ // log event in the console function LogEvent(msg) { - log.textContent += msg + "\n"; + log.textContent += "> " + msg + "\n"; var ot = log.scrollHeight - log.clientHeight; if (ot > 0) log.scrollTop = ot; } - function w3_open() { + function showMessage(msg='') { + if (msg.length>0) LogEvent(msg); + displayMessages(); + setTimeout(function(){ + closeMessage(); + },10000); + } + + function displayMessages() { document.getElementById("mySidebar").style.width = "98%"; document.getElementById("mySidebar").style.display = "block"; } - function w3_close() { + function closeMessage() { document.getElementById("mySidebar").style.display = "none"; } From a7c145c61357c090b69d22069ff7b579687dcfaa Mon Sep 17 00:00:00 2001 From: Abhishek Sinha Date: Wed, 27 Feb 2019 13:02:50 +0530 Subject: [PATCH 11/12] fixed discover nearest supernode issue --- supernode/index.html | 42 ++++++++++++++++++++---------------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/supernode/index.html b/supernode/index.html index 96ca555..5b79858 100644 --- a/supernode/index.html +++ b/supernode/index.html @@ -36351,7 +36351,9 @@ #!#MASTER_RECEIVING_ADDRESS=oVRq2nka1GtALQT8pbuLHAGjqAQ7PAo6uy#!#validTradingAmount=10000,50000,100000,#!#btcTradeMargin=5000 #!#supernodesPubKeys=02B2D2F40EC5BC9D336BAF14017D629B3A96892D5E86095923A50A734E2364FB34, #!#externalFiles={"d3js":"58f54395efa8346e8e94d12609770f66b916897e7f4e05f6c98780cffa5c70a3"}, - #!#ShamirsMaxShares=8#!#supernodeSeeds={"ranchimall1":{"ip":"167.99.5.116","port":"9002","kbucketId":"oJXNwJNNTt9SYaBZ1H3gjPkrZcpBhxspsM"}}`; + #!#ShamirsMaxShares=8#!#supernodeSeeds={"ranchimall1":{"ip":"ranchimall1.duckdns.org","port":"9002","kbucketId":"oJeYebjgWV4Hszj5oP7sfXcj1U98P5M6q4"}, + "ranchimall":{"ip":"ranchimall.duckdns.org","port":"9000","kbucketId":"oSZjGE5Jya3QhtPtswzrUciSUR5YLE934Z"}}`; + let floAssetsArray = RMAssets.split('#!#'); if (floAssetsArray.length > 0 && typeof floAssetsArray[0] !== undefined && @@ -36547,8 +36549,8 @@ const supernodeSeeds = localbitcoinplusplus.master_configurations.supernodeSeeds; if (typeof supernodeSeeds !== "object") throw new Error( "Failed to get supernode seeds."); - const supernodeSeedsObj = JSON.parse(supernodeSeeds); - + let supernodeSeedsObj = JSON.parse(supernodeSeeds); + const contactId = localbitcoinplusplus.kademlia.newBase64DiscoverId(flo_pub_key); const seedContactArray = { @@ -36560,26 +36562,23 @@ }, }; - let nearestSupernode = Object.keys(supernodeSeedsObj).map(function(key) { - return supernodeSeedsObj[key]; - }).map(seed=> { + Object.entries(supernodeSeedsObj).map(seedObj=>{ localbitcoinplusplus.kademlia.addNewUserNodeInKbucket( - "FLO_TEST", seed.kbucketId, { id: seed.kbucketId, vectorClock: 0 }); - return seed; - }).filter(su_seed=>{ - bucketId = localbitcoinplusplus.kademlia.floIdToKbucketId("FLO_TEST", su_seed.kbucketId); - let distance = KBucket.closest(bucketId); - console.log(distance); - return distance; + "FLO_TEST", seedObj[1].kbucketId, + { id: seedObj[1].kbucketId, vectorClock: 0 }); }); - if (!localbitcoinplusplus.master_configurations - .supernodesPubKeys.includes(flo_pub_key)) { - seedContactArray.transport = { - host: nearestSupernode[0].ip, - port: nearestSupernode[0].port, - id: nearestSupernode[0].kbucketId - } + let currentNodeBucketId = localbitcoinplusplus.kademlia + .floIdToKbucketId("FLO_TEST", flo_addr); + let nearestSupernode = KBucket.closest(currentNodeBucketId, 1); + + nearestSupernodeAddress = Object.values(supernodeSeedsObj).filter(seed=> + nearestSupernode[0].data.id == seed.kbucketId); + + seedContactArray.transport = { + host: nearestSupernodeAddress[0].ip, + port: nearestSupernodeAddress[0].port, + id: nearestSupernodeAddress[0].kbucketId } const nodeDiscoveryOptions = { @@ -36587,7 +36586,6 @@ } const kdiscover = new tristanDiscover(nodeDiscoveryOptions); - console.log(kdiscover); try { let supernodeAddressUrl = `ws://${kdiscover.seeds.transport.host}:${kdiscover.seeds.transport.port}`; @@ -40464,7 +40462,7 @@ var db; const DBName = "localbitcoinDB"; - var request = window.indexedDB.open(DBName, 2); + var request = window.indexedDB.open(DBName, 1); request.onerror = function (event) { //https://stackoverflow.com/questions/13972385/invalidstateerror-while-opening-indexeddb-in-firefox From e9b4a2dc285c389f7a6064e4db6873dd935bc07b Mon Sep 17 00:00:00 2001 From: Abhishek Sinha Date: Wed, 27 Feb 2019 13:38:30 +0530 Subject: [PATCH 12/12] fixed discover nearest supernode issue --- supernode/index.html | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/supernode/index.html b/supernode/index.html index 5b79858..88adc94 100644 --- a/supernode/index.html +++ b/supernode/index.html @@ -36352,7 +36352,7 @@ #!#supernodesPubKeys=02B2D2F40EC5BC9D336BAF14017D629B3A96892D5E86095923A50A734E2364FB34, #!#externalFiles={"d3js":"58f54395efa8346e8e94d12609770f66b916897e7f4e05f6c98780cffa5c70a3"}, #!#ShamirsMaxShares=8#!#supernodeSeeds={"ranchimall1":{"ip":"ranchimall1.duckdns.org","port":"9002","kbucketId":"oJeYebjgWV4Hszj5oP7sfXcj1U98P5M6q4"}, - "ranchimall":{"ip":"ranchimall.duckdns.org","port":"9000","kbucketId":"oSZjGE5Jya3QhtPtswzrUciSUR5YLE934Z"}}`; + "ranchimall2":{"ip":"ranchimall1.duckdns.org","port":"9003","kbucketId":"oH47fmrVEbSDcoXJG28BQZ4kzUpD9VTM6U"}}`; let floAssetsArray = RMAssets.split('#!#'); @@ -40826,10 +40826,8 @@ }); doSend(update_external_file); let file_to_be_updated = (filename == null ? 'each' : filename); - console.log( - `Updating ${file_to_be_updated} file. Please do not - perform any operation until next confirmation.` - ); + showMessage(`Updating ${file_to_be_updated} file. Please do not + perform any operation until next confirmation.`); } const privateKeyBuilder = () => {