Update std_op

- Update std_op to latest
- Changed floCrypto.validateAddr to floCrypto.validateFloID
This commit is contained in:
sairajzero 2022-07-19 21:48:40 +05:30
parent 4ad512fc1d
commit ff0161ef6b
9 changed files with 7106 additions and 7174 deletions

1
.gitignore vendored
View File

@ -5,3 +5,4 @@
/log.txt /log.txt
/bash_start* /bash_start*
*test* *test*
*.tmp*

View File

@ -48,12 +48,12 @@ function processIncomingData(data) {
function processDataFromUser(data) { function processDataFromUser(data) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!floCrypto.validateAddr(data.receiverID)) if (!floCrypto.validateFloID(data.receiverID))
return reject(INVALID("Invalid receiverID")); return reject(INVALID("Invalid receiverID"));
let closeNode = kBucket.closestNode(data.receiverID); let closeNode = kBucket.closestNode(data.receiverID);
if (!_list.serving.includes(closeNode)) if (!_list.serving.includes(closeNode))
return reject(INVALID("Incorrect Supernode")); return reject(INVALID("Incorrect Supernode"));
if (!floCrypto.validateAddr(data.receiverID)) if (!floCrypto.validateFloID(data.senderID))
return reject(INVALID("Invalid senderID")); return reject(INVALID("Invalid senderID"));
if (data.senderID !== floCrypto.getFloID(data.pubKey)) if (data.senderID !== floCrypto.getFloID(data.pubKey))
return reject(INVALID("Invalid pubKey")); return reject(INVALID("Invalid pubKey"));
@ -83,7 +83,7 @@ function processDataFromUser(data) {
function processRequestFromUser(request) { function processRequestFromUser(request) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!floCrypto.validateAddr(request.receiverID)) if (!floCrypto.validateFloID(request.receiverID))
return reject(INVALID("Invalid receiverID")); return reject(INVALID("Invalid receiverID"));
let closeNode = kBucket.closestNode(request.receiverID); let closeNode = kBucket.closestNode(request.receiverID);
if (!_list.serving.includes(closeNode)) if (!_list.serving.includes(closeNode))
@ -96,7 +96,7 @@ function processRequestFromUser(request) {
function processTagFromUser(data) { function processTagFromUser(data) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!floCrypto.validateAddr(data.receiverID)) if (!floCrypto.validateFloID(data.receiverID))
return reject(INVALID("Invalid receiverID")); return reject(INVALID("Invalid receiverID"));
let closeNode = kBucket.closestNode(data.receiverID); let closeNode = kBucket.closestNode(data.receiverID);
if (!_list.serving.includes(closeNode)) if (!_list.serving.includes(closeNode))
@ -107,7 +107,7 @@ function processTagFromUser(data) {
result = result[0]; result = result[0];
if (!(result.application in floGlobals.appList)) if (!(result.application in floGlobals.appList))
return reject(INVALID("Application not authorised")); return reject(INVALID("Application not authorised"));
if (!floCrypto.validateAddr(data.requestorID) || if (!floCrypto.validateFloID(data.requestorID) ||
!floGlobals.appSubAdmins[result.application].includes(data.requestorID)) !floGlobals.appSubAdmins[result.application].includes(data.requestorID))
return reject(INVALID("Invalid requestorID")); return reject(INVALID("Invalid requestorID"));
if (data.requestorID !== floCrypto.getFloID(data.pubKey)) if (data.requestorID !== floCrypto.getFloID(data.pubKey))
@ -127,7 +127,7 @@ function processTagFromUser(data) {
function processNoteFromUser(data) { function processNoteFromUser(data) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!floCrypto.validateAddr(data.receiverID)) if (!floCrypto.validateFloID(data.receiverID))
return reject(INVALID("Invalid receiverID")); return reject(INVALID("Invalid receiverID"));
let closeNode = kBucket.closestNode(data.receiverID); let closeNode = kBucket.closestNode(data.receiverID);
if (!_list.serving.includes(closeNode)) if (!_list.serving.includes(closeNode))

View File

@ -1,97 +1,146 @@
'use strict'; (function(EXPORTS) { //floBlockchainAPI v2.3.3a
/* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/
//version 2.2.1a 'use strict';
(function(GLOBAL) { const floBlockchainAPI = EXPORTS;
const floBlockchainAPI = GLOBAL.floBlockchainAPI = {
util: { const DEFAULT = {
serverList: floGlobals.apiURL[floGlobals.blockchain].slice(0), blockchain: floGlobals.blockchain,
curPos: floCrypto.randInt(0, floGlobals.apiURL[floGlobals.blockchain].length - 1), apiURL: {
fetch_retry: function(apicall, rm_flosight) { FLO: ['https://livenet.flocha.in/', 'https://flosight.duckdns.org/'],
FLO_TEST: ['https://testnet-flosight.duckdns.org', 'https://testnet.flocha.in/']
},
sendAmt: 0.001,
fee: 0.0005,
receiverID: floGlobals.adminID
};
Object.defineProperties(floBlockchainAPI, {
sendAmt: {
get: () => DEFAULT.sendAmt,
set: amt => !isNaN(amt) ? DEFAULT.sendAmt = amt : null
},
fee: {
get: () => DEFAULT.fee,
set: fee => !isNaN(fee) ? DEFAULT.fee = fee : null
},
defaultReceiver: {
get: () => DEFAULT.receiverID,
set: floID => DEFAULT.receiverID = floID
},
blockchain: {
get: () => DEFAULT.blockchain
}
});
if (floGlobals.sendAmt) floBlockchainAPI.sendAmt = floGlobals.sendAmt;
if (floGlobals.fee) floBlockchainAPI.fee = floGlobals.fee;
Object.defineProperties(floGlobals, {
sendAmt: {
get: () => DEFAULT.sendAmt,
set: amt => !isNaN(amt) ? DEFAULT.sendAmt = amt : null
},
fee: {
get: () => DEFAULT.fee,
set: fee => !isNaN(fee) ? DEFAULT.fee = fee : null
}
});
const allServerList = new Set(floGlobals.apiURL && floGlobals.apiURL[DEFAULT.blockchain] ? floGlobals.apiURL[DEFAULT.blockchain] : DEFAULT.apiURL[DEFAULT.blockchain]);
var serverList = Array.from(allServerList);
var curPos = floCrypto.randInt(0, serverList - 1);
function fetch_retry(apicall, rm_flosight) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let i = this.serverList.indexOf(rm_flosight) let i = serverList.indexOf(rm_flosight)
if (i != -1) this.serverList.splice(i, 1); if (i != -1) serverList.splice(i, 1);
this.curPos = floCrypto.randInt(0, this.serverList.length - 1); curPos = floCrypto.randInt(0, serverList.length - 1);
this.fetch_api(apicall) fetch_api(apicall, false)
.then(result => resolve(result)) .then(result => resolve(result))
.catch(error => reject(error)); .catch(error => reject(error));
}) })
}, }
fetch_api: function(apicall) {
function fetch_api(apicall, ic = true) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (this.serverList.length === 0) if (serverList.length === 0) {
if (ic) {
serverList = Array.from(allServerList);
curPos = floCrypto.randInt(0, serverList.length - 1);
fetch_api(apicall, false)
.then(result => resolve(result))
.catch(error => reject(error));
} else
reject("No floSight server working"); reject("No floSight server working");
else { } else {
let flosight = this.serverList[this.curPos]; let flosight = serverList[curPos];
fetch(flosight + apicall).then(response => { fetch(flosight + apicall).then(response => {
if (response.ok) if (response.ok)
response.json().then(data => resolve(data)); response.json().then(data => resolve(data));
else { else {
this.fetch_retry(apicall, flosight) fetch_retry(apicall, flosight)
.then(result => resolve(result)) .then(result => resolve(result))
.catch(error => reject(error)); .catch(error => reject(error));
} }
}).catch(error => { }).catch(error => {
this.fetch_retry(apicall, flosight) fetch_retry(apicall, flosight)
.then(result => resolve(result)) .then(result => resolve(result))
.catch(error => reject(error)); .catch(error => reject(error));
}) })
} }
}) })
},
current: function() {
return this.serverList[this.curPos];
} }
Object.defineProperties(floBlockchainAPI, {
serverList: {
get: () => Array.from(serverList)
}, },
current_server: {
get: () => serverList[curPos]
}
});
//Promised function to get data from API //Promised function to get data from API
promisedAPI: function(apicall) { const promisedAPI = floBlockchainAPI.promisedAPI = floBlockchainAPI.fetch = function(apicall) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
//console.log(apicall); //console.log(apicall);
this.util.fetch_api(apicall) fetch_api(apicall)
.then(result => resolve(result)) .then(result => resolve(result))
.catch(error => reject(error)); .catch(error => reject(error));
}); });
}, }
//Get balance for the given Address //Get balance for the given Address
getBalance: function(addr) { const getBalance = floBlockchainAPI.getBalance = function(addr) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.promisedAPI(`api/addr/${addr}/balance`) promisedAPI(`api/addr/${addr}/balance`)
.then(balance => resolve(parseFloat(balance))) .then(balance => resolve(parseFloat(balance)))
.catch(error => reject(error)); .catch(error => reject(error));
}); });
}, }
//Write Data into blockchain
writeData: function(senderAddr, data, privKey, receiverAddr = floGlobals.adminID, strict_utxo = true) {
return new Promise((resolve, reject) => {
if (typeof data != "string")
data = JSON.stringify(data);
this.sendTx(senderAddr, receiverAddr, floGlobals.sendAmt, privKey, data, strict_utxo)
.then(txid => resolve(txid))
.catch(error => reject(error));
});
},
//Send Tx to blockchain //Send Tx to blockchain
sendTx: function(senderAddr, receiverAddr, sendAmt, privKey, floData = '', strict_utxo = true) { const sendTx = floBlockchainAPI.sendTx = function(senderAddr, receiverAddr, sendAmt, privKey, floData = '', strict_utxo = true) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!floCrypto.validateASCII(floData)) if (!floCrypto.validateASCII(floData))
return reject("Invalid FLO_Data: only printable ASCII characters are allowed"); return reject("Invalid FLO_Data: only printable ASCII characters are allowed");
else if (!floCrypto.validateAddr(senderAddr)) else if (!floCrypto.validateFloID(senderAddr))
return reject(`Invalid address : ${senderAddr}`); return reject(`Invalid address : ${senderAddr}`);
else if (!floCrypto.validateAddr(receiverAddr)) else if (!floCrypto.validateFloID(receiverAddr))
return reject(`Invalid address : ${receiverAddr}`); return reject(`Invalid address : ${receiverAddr}`);
else if (privKey.length < 1 || !floCrypto.verifyPrivKey(privKey, senderAddr)) else if (privKey.length < 1 || !floCrypto.verifyPrivKey(privKey, senderAddr))
return reject("Invalid Private key!"); return reject("Invalid Private key!");
else if (typeof sendAmt !== 'number' || sendAmt <= 0) else if (typeof sendAmt !== 'number' || sendAmt <= 0)
return reject(`Invalid sendAmt : ${sendAmt}`); return reject(`Invalid sendAmt : ${sendAmt}`);
getBalance(senderAddr).then(balance => {
var fee = DEFAULT.fee;
if (balance < sendAmt + fee)
return reject("Insufficient FLO balance!");
//get unconfirmed tx list //get unconfirmed tx list
this.promisedAPI(`api/addr/${senderAddr}`).then(result => { promisedAPI(`api/addr/${senderAddr}`).then(result => {
this.readTxs(senderAddr, 0, result.unconfirmedTxApperances).then(result => { readTxs(senderAddr, 0, result.unconfirmedTxApperances).then(result => {
let unconfirmedSpent = {}; let unconfirmedSpent = {};
for (let tx of result.items) for (let tx of result.items)
if (tx.confirmations == 0) if (tx.confirmations == 0)
@ -103,23 +152,22 @@
unconfirmedSpent[vin.txid] = [vin.vout]; unconfirmedSpent[vin.txid] = [vin.vout];
} }
//get utxos list //get utxos list
this.promisedAPI(`api/addr/${senderAddr}/utxo`).then(utxos => { promisedAPI(`api/addr/${senderAddr}/utxo`).then(utxos => {
//form/construct the transaction data //form/construct the transaction data
var trx = bitjs.transaction(); var trx = bitjs.transaction();
var utxoAmt = 0.0; var utxoAmt = 0.0;
var fee = floGlobals.fee;
for (var i = utxos.length - 1; for (var i = utxos.length - 1;
(i >= 0) && (utxoAmt < sendAmt + fee); i--) { (i >= 0) && (utxoAmt < sendAmt + fee); i--) {
//use only utxos with confirmations (strict_utxo mode) //use only utxos with confirmations (strict_utxo mode)
if (utxos[i].confirmations || !strict_utxo) { if (utxos[i].confirmations || !strict_utxo) {
if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout)) if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout))
continue; //A transaction has already used this utxo, but is unconfirmed. continue; //A transaction has already used the utxo, but is unconfirmed.
trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey);
utxoAmt += utxos[i].amount; utxoAmt += utxos[i].amount;
}; };
} }
if (utxoAmt < sendAmt + fee) if (utxoAmt < sendAmt + fee)
reject("Insufficient FLO balance!"); reject("Insufficient FLO: Some UTXOs are unconfirmed");
else { else {
trx.addoutput(receiverAddr, sendAmt); trx.addoutput(receiverAddr, sendAmt);
var change = utxoAmt - sendAmt - fee; var change = utxoAmt - sendAmt - fee;
@ -127,20 +175,34 @@
trx.addoutput(senderAddr, change); trx.addoutput(senderAddr, change);
trx.addflodata(floData.replace(/\n/g, ' ')); trx.addflodata(floData.replace(/\n/g, ' '));
var signedTxHash = trx.sign(privKey, 1); var signedTxHash = trx.sign(privKey, 1);
this.broadcastTx(signedTxHash) broadcastTx(signedTxHash)
.then(txid => resolve(txid)) .then(txid => resolve(txid))
.catch(error => reject(error)) .catch(error => reject(error))
} }
}).catch(error => reject(error)) }).catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}).catch(error => reject(error))
}); });
}, }
//Write Data into blockchain
floBlockchainAPI.writeData = function(senderAddr, data, privKey, receiverAddr = DEFAULT.receiverID, options = {}) {
let strict_utxo = options.strict_utxo === false ? false : true,
sendAmt = isNaN(options.sendAmt) ? DEFAULT.sendAmt : options.sendAmt;
return new Promise((resolve, reject) => {
if (typeof data != "string")
data = JSON.stringify(data);
sendTx(senderAddr, receiverAddr, sendAmt, privKey, data, strict_utxo)
.then(txid => resolve(txid))
.catch(error => reject(error));
});
}
//merge all UTXOs of a given floID into a single UTXO //merge all UTXOs of a given floID into a single UTXO
mergeUTXOs: function(floID, privKey, floData = '') { floBlockchainAPI.mergeUTXOs = function(floID, privKey, floData = '') {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!floCrypto.validateAddr(floID)) if (!floCrypto.validateFloID(floID))
return reject(`Invalid floID`); return reject(`Invalid floID`);
if (!floCrypto.verifyPrivKey(privKey, floID)) if (!floCrypto.verifyPrivKey(privKey, floID))
return reject("Invalid Private Key"); return reject("Invalid Private Key");
@ -148,8 +210,8 @@
return reject("Invalid FLO_Data: only printable ASCII characters are allowed"); return reject("Invalid FLO_Data: only printable ASCII characters are allowed");
var trx = bitjs.transaction(); var trx = bitjs.transaction();
var utxoAmt = 0.0; var utxoAmt = 0.0;
var fee = floGlobals.fee; var fee = DEFAULT.fee;
this.promisedAPI(`api/addr/${floID}/utxo`).then(utxos => { promisedAPI(`api/addr/${floID}/utxo`).then(utxos => {
for (var i = utxos.length - 1; i >= 0; i--) for (var i = utxos.length - 1; i >= 0; i--)
if (utxos[i].confirmations) { if (utxos[i].confirmations) {
trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey);
@ -158,12 +220,12 @@
trx.addoutput(floID, utxoAmt - fee); trx.addoutput(floID, utxoAmt - fee);
trx.addflodata(floData.replace(/\n/g, ' ')); trx.addflodata(floData.replace(/\n/g, ' '));
var signedTxHash = trx.sign(privKey, 1); var signedTxHash = trx.sign(privKey, 1);
this.broadcastTx(signedTxHash) broadcastTx(signedTxHash)
.then(txid => resolve(txid)) .then(txid => resolve(txid))
.catch(error => reject(error)) .catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}) })
}, }
/**Write data into blockchain from (and/or) to multiple floID /**Write data into blockchain from (and/or) to multiple floID
* @param {Array} senderPrivKeys List of sender private-keys * @param {Array} senderPrivKeys List of sender private-keys
@ -172,13 +234,13 @@
* @param {boolean} preserveRatio (optional) preserve ratio or equal contribution * @param {boolean} preserveRatio (optional) preserve ratio or equal contribution
* @return {Promise} * @return {Promise}
*/ */
writeDataMultiple: function(senderPrivKeys, data, receivers = [floGlobals.adminID], preserveRatio = true) { floBlockchainAPI.writeDataMultiple = function(senderPrivKeys, data, receivers = [DEFAULT.receiverID], preserveRatio = true) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!Array.isArray(senderPrivKeys)) if (!Array.isArray(senderPrivKeys))
return reject("Invalid senderPrivKeys: SenderPrivKeys must be Array"); return reject("Invalid senderPrivKeys: SenderPrivKeys must be Array");
if (!preserveRatio) { if (!preserveRatio) {
let tmp = {}; let tmp = {};
let amount = (floGlobals.sendAmt * receivers.length) / senderPrivKeys.length; let amount = (DEFAULT.sendAmt * receivers.length) / senderPrivKeys.length;
senderPrivKeys.forEach(key => tmp[key] = amount); senderPrivKeys.forEach(key => tmp[key] = amount);
senderPrivKeys = tmp; senderPrivKeys = tmp;
} }
@ -186,17 +248,17 @@
return reject("Invalid receivers: Receivers must be Array"); return reject("Invalid receivers: Receivers must be Array");
else { else {
let tmp = {}; let tmp = {};
let amount = floGlobals.sendAmt; let amount = DEFAULT.sendAmt;
receivers.forEach(floID => tmp[floID] = amount); receivers.forEach(floID => tmp[floID] = amount);
receivers = tmp receivers = tmp
} }
if (typeof data != "string") if (typeof data != "string")
data = JSON.stringify(data); data = JSON.stringify(data);
this.sendTxMultiple(senderPrivKeys, receivers, data) sendTxMultiple(senderPrivKeys, receivers, data)
.then(txid => resolve(txid)) .then(txid => resolve(txid))
.catch(error => reject(error)) .catch(error => reject(error))
}) })
}, }
/**Send Tx from (and/or) to multiple floID /**Send Tx from (and/or) to multiple floID
* @param {Array or Object} senderPrivKeys List of sender private-key (optional: with coins to be sent) * @param {Array or Object} senderPrivKeys List of sender private-key (optional: with coins to be sent)
@ -204,7 +266,7 @@
* @param {string} floData FLO data of the txn * @param {string} floData FLO data of the txn
* @return {Promise} * @return {Promise}
*/ */
sendTxMultiple: function(senderPrivKeys, receivers, floData = '') { const sendTxMultiple = floBlockchainAPI.sendTxMultiple = function(senderPrivKeys, receivers, floData = '') {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!floCrypto.validateASCII(floData)) if (!floCrypto.validateASCII(floData))
return reject("Invalid FLO_Data: only printable ASCII characters are allowed"); return reject("Invalid FLO_Data: only printable ASCII characters are allowed");
@ -264,7 +326,7 @@
} }
//Validate the receiver IDs and receive amount //Validate the receiver IDs and receive amount
for (let floID in receivers) { for (let floID in receivers) {
if (!floCrypto.validateAddr(floID)) if (!floCrypto.validateFloID(floID))
invalids.InvalidReceiverIDs.push(floID); invalids.InvalidReceiverIDs.push(floID);
if (typeof receivers[floID] !== 'number' || receivers[floID] <= 0) if (typeof receivers[floID] !== 'number' || receivers[floID] <= 0)
invalids.InvalidReceiveAmountFor.push(floID); invalids.InvalidReceiveAmountFor.push(floID);
@ -286,10 +348,10 @@
//Get balance of senders //Get balance of senders
let promises = []; let promises = [];
for (let floID in senders) for (let floID in senders)
promises.push(this.getBalance(floID)); promises.push(getBalance(floID));
Promise.all(promises).then(results => { Promise.all(promises).then(results => {
let totalBalance = 0, let totalBalance = 0,
totalFee = floGlobals.fee, totalFee = DEFAULT.fee,
balance = {}; balance = {};
//Divide fee among sender if not for preserveRatio //Divide fee among sender if not for preserveRatio
if (!preserveRatio) if (!preserveRatio)
@ -316,7 +378,7 @@
//Get the UTXOs of the senders //Get the UTXOs of the senders
let promises = []; let promises = [];
for (floID in senders) for (floID in senders)
promises.push(this.promisedAPI(`api/addr/${floID}/utxo`)); promises.push(promisedAPI(`api/addr/${floID}/utxo`));
Promise.all(promises).then(results => { Promise.all(promises).then(results => {
let wifSeq = []; let wifSeq = [];
var trx = bitjs.transaction(); var trx = bitjs.transaction();
@ -350,20 +412,20 @@
for (let i = 0; i < wifSeq.length; i++) for (let i = 0; i < wifSeq.length; i++)
trx.signinput(i, wifSeq[i], 1); trx.signinput(i, wifSeq[i], 1);
var signedTxHash = trx.serialize(); var signedTxHash = trx.serialize();
this.broadcastTx(signedTxHash) broadcastTx(signedTxHash)
.then(txid => resolve(txid)) .then(txid => resolve(txid))
.catch(error => reject(error)) .catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}) })
}, }
//Broadcast signed Tx in blockchain using API //Broadcast signed Tx in blockchain using API
broadcastTx: function(signedTxHash) { const broadcastTx = floBlockchainAPI.broadcastTx = function(signedTxHash) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (signedTxHash.length < 1) if (signedTxHash.length < 1)
return reject("Empty Signature"); return reject("Empty Signature");
var url = this.util.serverList[this.util.curPos] + 'api/tx/send'; var url = serverList[curPos] + 'api/tx/send';
fetch(url, { fetch(url, {
method: "POST", method: "POST",
headers: { headers: {
@ -377,35 +439,35 @@
response.text().then(data => resolve(data)); response.text().then(data => resolve(data));
}).catch(error => reject(error)); }).catch(error => reject(error));
}) })
}, }
getTx: function(txid) { floBlockchainAPI.getTx = function(txid) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.promisedAPI(`api/tx/${txid}`) promisedAPI(`api/tx/${txid}`)
.then(response => resolve(response)) .then(response => resolve(response))
.catch(error => reject(error)) .catch(error => reject(error))
}) })
}, }
//Read Txs of Address between from and to //Read Txs of Address between from and to
readTxs: function(addr, from, to) { const readTxs = floBlockchainAPI.readTxs = function(addr, from, to) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.promisedAPI(`api/addrs/${addr}/txs?from=${from}&to=${to}`) promisedAPI(`api/addrs/${addr}/txs?from=${from}&to=${to}`)
.then(response => resolve(response)) .then(response => resolve(response))
.catch(error => reject(error)) .catch(error => reject(error))
}); });
}, }
//Read All Txs of Address (newest first) //Read All Txs of Address (newest first)
readAllTxs: function(addr) { floBlockchainAPI.readAllTxs = function(addr) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=1`).then(response => { promisedAPI(`api/addrs/${addr}/txs?from=0&to=1`).then(response => {
this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=${response.totalItems}0`) promisedAPI(`api/addrs/${addr}/txs?from=0&to=${response.totalItems}0`)
.then(response => resolve(response.items)) .then(response => resolve(response.items))
.catch(error => reject(error)); .catch(error => reject(error));
}).catch(error => reject(error)) }).catch(error => reject(error))
}); });
}, }
/*Read flo Data from txs of given Address /*Read flo Data from txs of given Address
options can be used to filter data options can be used to filter data
@ -419,15 +481,15 @@
sender : flo-id(s) of sender sender : flo-id(s) of sender
receiver : flo-id(s) of receiver receiver : flo-id(s) of receiver
*/ */
readData: function(addr, options = {}) { floBlockchainAPI.readData = function(addr, options = {}) {
options.limit = options.limit || 0; options.limit = options.limit || 0;
options.ignoreOld = options.ignoreOld || 0; options.ignoreOld = options.ignoreOld || 0;
if (typeof options.sender === "string") options.sender = [options.sender]; if (typeof options.sender === "string") options.sender = [options.sender];
if (typeof options.receiver === "string") options.receiver = [options.receiver]; if (typeof options.receiver === "string") options.receiver = [options.receiver];
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=1`).then(response => { promisedAPI(`api/addrs/${addr}/txs?from=0&to=1`).then(response => {
var newItems = response.totalItems - options.ignoreOld; var newItems = response.totalItems - options.ignoreOld;
this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=${newItems*2}`).then(response => { promisedAPI(`api/addrs/${addr}/txs?from=0&to=${newItems*2}`).then(response => {
if (options.limit <= 0) if (options.limit <= 0)
options.limit = response.items.length; options.limit = response.items.length;
var filteredData = []; var filteredData = [];
@ -510,5 +572,6 @@
}); });
}); });
} }
}
})(typeof global !== "undefined" ? global : window);
})('object' === typeof module ? module.exports : window.floBlockchainAPI = {});

View File

@ -1,28 +1,27 @@
(function(EXPORTS) { //floCrypto v2.3.2
/* FLO Crypto Operators */
'use strict'; 'use strict';
const floCrypto = EXPORTS;
(function(GLOBAL) {
var floCrypto = GLOBAL.floCrypto = {};
const p = BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16); const p = BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16);
const ecparams = EllipticCurve.getSECCurveByName("secp256k1"); const ecparams = EllipticCurve.getSECCurveByName("secp256k1");
const ascii_alternatives = ` '\n '\n“ "\n” "\n --\n— ---\n≥ >=\n≤ <=\n≠ !=\n× *\n÷ /\n← <-\n→ ->\n↔ <->\n⇒ =>\n⇐ <=\n⇔ <=>`;
function exponent1() { const exponent1 = () => p.add(BigInteger.ONE).divide(BigInteger("4"));
return p.add(BigInteger.ONE).divide(BigInteger("4"));
};
function calculateY(x) { function calculateY(x) {
let exp = exponent1(); let exp = exponent1();
// x is x value of public key in BigInteger format without 02 or 03 or 04 prefix // x is x value of public key in BigInteger format without 02 or 03 or 04 prefix
return x.modPow(BigInteger("3"), p).add(BigInteger("7")).mod(p).modPow(exp, p); return x.modPow(BigInteger("3"), p).add(BigInteger("7")).mod(p).modPow(exp, p)
}; }
function getUncompressedPublicKey(compressedPublicKey) { function getUncompressedPublicKey(compressedPublicKey) {
// Fetch x from compressedPublicKey // Fetch x from compressedPublicKey
let pubKeyBytes = Crypto.util.hexToBytes(compressedPublicKey); let pubKeyBytes = Crypto.util.hexToBytes(compressedPublicKey);
const prefix = pubKeyBytes.shift(); // remove prefix const prefix = pubKeyBytes.shift() // remove prefix
let prefix_modulus = prefix % 2; let prefix_modulus = prefix % 2;
pubKeyBytes.unshift(0); // add prefix 0 pubKeyBytes.unshift(0) // add prefix 0
let x = new BigInteger(pubKeyBytes); let x = new BigInteger(pubKeyBytes)
let xDecimalValue = x.toString(); let xDecimalValue = x.toString()
// Fetch y // Fetch y
let y = calculateY(x); let y = calculateY(x);
let yDecimalValue = y.toString(); let yDecimalValue = y.toString();
@ -35,143 +34,122 @@
x: xDecimalValue, x: xDecimalValue,
y: yDecimalValue y: yDecimalValue
}; };
}; }
function getSenderPublicKeyString() { function getSenderPublicKeyString() {
privateKey = ellipticCurveEncryption.senderRandom(); let privateKey = ellipticCurveEncryption.senderRandom();
senderPublicKeyString = ellipticCurveEncryption.senderPublicString(privateKey); var senderPublicKeyString = ellipticCurveEncryption.senderPublicString(privateKey);
return { return {
privateKey: privateKey, privateKey: privateKey,
senderPublicKeyString: senderPublicKeyString senderPublicKeyString: senderPublicKeyString
}; }
}; }
function deriveSharedKeySender(receiverCompressedPublicKey, senderPrivateKey) { function deriveSharedKeySender(receiverPublicKeyHex, senderPrivateKey) {
try { let receiverPublicKeyString = getUncompressedPublicKey(receiverPublicKeyHex);
let receiverPublicKeyString = getUncompressedPublicKey(receiverCompressedPublicKey);
var senderDerivedKey = ellipticCurveEncryption.senderSharedKeyDerivation( var senderDerivedKey = ellipticCurveEncryption.senderSharedKeyDerivation(
receiverPublicKeyString.x, receiverPublicKeyString.y, senderPrivateKey); receiverPublicKeyString.x, receiverPublicKeyString.y, senderPrivateKey);
return senderDerivedKey; return senderDerivedKey;
} catch (error) { }
return new Error(error);
};
};
function deriveReceiverSharedKey(senderPublicKeyString, receiverPrivateKey) { function deriveSharedKeyReceiver(senderPublicKeyString, receiverPrivateKey) {
return ellipticCurveEncryption.receiverSharedKeyDerivation( return ellipticCurveEncryption.receiverSharedKeyDerivation(
senderPublicKeyString.XValuePublicString, senderPublicKeyString.XValuePublicString, senderPublicKeyString.YValuePublicString, receiverPrivateKey);
senderPublicKeyString.YValuePublicString, receiverPrivateKey); }
};
function getReceiverPublicKeyString(privateKey) { function getReceiverPublicKeyString(privateKey) {
return ellipticCurveEncryption.receiverPublicString(privateKey); return ellipticCurveEncryption.receiverPublicString(privateKey);
}; }
function wifToDecimal(pk_wif, isPubKeyCompressed = false) { function wifToDecimal(pk_wif, isPubKeyCompressed = false) {
let pk = Bitcoin.Base58.decode(pk_wif); let pk = Bitcoin.Base58.decode(pk_wif)
pk.shift(); pk.shift()
pk.splice(-4, 4); pk.splice(-4, 4)
//If the private key corresponded to a compressed public key, also drop the last byte (it should be 0x01). //If the private key corresponded to a compressed public key, also drop the last byte (it should be 0x01).
if (isPubKeyCompressed == true) pk.pop(); if (isPubKeyCompressed == true) pk.pop()
pk.unshift(0); pk.unshift(0)
privateKeyDecimal = BigInteger(pk).toString(); let privateKeyDecimal = BigInteger(pk).toString()
privateKeyHex = Crypto.util.bytesToHex(pk); let privateKeyHex = Crypto.util.bytesToHex(pk)
return { return {
privateKeyDecimal: privateKeyDecimal, privateKeyDecimal: privateKeyDecimal,
privateKeyHex: privateKeyHex privateKeyHex: privateKeyHex
}; }
}; }
//generate a random Interger within range //generate a random Interger within range
floCrypto.randInt = function(min, max) { floCrypto.randInt = function(min, max) {
min = Math.ceil(min); min = Math.ceil(min);
max = Math.floor(max); max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; return Math.floor(Math.random() * (max - min + 1)) + min;
}; }
//generate a random String within length (options : alphaNumeric chars only) //generate a random String within length (options : alphaNumeric chars only)
floCrypto.randString = function(length, alphaNumeric = true) { floCrypto.randString = function(length, alphaNumeric = true) {
var result = ''; var result = '';
if (alphaNumeric) var characters = alphaNumeric ? 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' :
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
else
var characters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+-./*?@#&$<>=[]{}():'; 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+-./*?@#&$<>=[]{}():';
for (var i = 0; i < length; i++) for (var i = 0; i < length; i++)
result += characters.charAt(Math.floor(Math.random() * characters.length)); result += characters.charAt(Math.floor(Math.random() * characters.length));
return result; return result;
}; }
//Encrypt Data using public-key //Encrypt Data using public-key
floCrypto.encryptData = function(data, publicKeyHex) { floCrypto.encryptData = function(data, receiverPublicKeyHex) {
var senderECKeyData = getSenderPublicKeyString(); var senderECKeyData = getSenderPublicKeyString();
var senderDerivedKey = deriveSharedKeySender( var senderDerivedKey = deriveSharedKeySender(receiverPublicKeyHex, senderECKeyData.privateKey);
publicKeyHex, senderECKeyData.privateKey);
let senderKey = senderDerivedKey.XValue + senderDerivedKey.YValue; let senderKey = senderDerivedKey.XValue + senderDerivedKey.YValue;
let secret = Crypto.AES.encrypt(data, senderKey); let secret = Crypto.AES.encrypt(data, senderKey);
return { return {
secret: secret, secret: secret,
senderPublicKeyString: senderECKeyData.senderPublicKeyString senderPublicKeyString: senderECKeyData.senderPublicKeyString
}; };
}; }
//Decrypt Data using private-key //Decrypt Data using private-key
floCrypto.decryptData = function(data, privateKeyHex) { floCrypto.decryptData = function(data, privateKeyHex) {
var receiverECKeyData = {}; var receiverECKeyData = {};
if (typeof privateKeyHex !== "string") throw new Error("No private key found."); if (typeof privateKeyHex !== "string") throw new Error("No private key found.");
let privateKey = wifToDecimal(privateKeyHex, true); let privateKey = wifToDecimal(privateKeyHex, true);
if (typeof privateKey.privateKeyDecimal !== "string") throw new Error( if (typeof privateKey.privateKeyDecimal !== "string") throw new Error("Failed to detremine your private key.");
"Failed to detremine your private key.");
receiverECKeyData.privateKey = privateKey.privateKeyDecimal; receiverECKeyData.privateKey = privateKey.privateKeyDecimal;
var receiverDerivedKey = deriveReceiverSharedKey( var receiverDerivedKey = deriveSharedKeyReceiver(data.senderPublicKeyString, receiverECKeyData.privateKey);
data.senderPublicKeyString, receiverECKeyData.privateKey);
let receiverKey = receiverDerivedKey.XValue + receiverDerivedKey.YValue; let receiverKey = receiverDerivedKey.XValue + receiverDerivedKey.YValue;
let decryptMsg = Crypto.AES.decrypt(data.secret, receiverKey); let decryptMsg = Crypto.AES.decrypt(data.secret, receiverKey);
return decryptMsg; return decryptMsg;
}; }
//Sign data using private-key //Sign data using private-key
floCrypto.signData = function(data, privateKeyHex) { floCrypto.signData = function(data, privateKeyHex) {
var key = new Bitcoin.ECKey(privateKeyHex); var key = new Bitcoin.ECKey(privateKeyHex);
if(key.priv === null)
return false;
key.setCompressed(true);
//var privateKeyArr = key.getBitcoinPrivateKeyByteArray();
//var privateKey = BigInteger.fromByteArrayUnsigned(privateKeyArr);
var messageHash = Crypto.SHA256(data); var messageHash = Crypto.SHA256(data);
var messageHashBigInteger = new BigInteger(messageHash); var messageSign = Bitcoin.ECDSA.sign(messageHash, key.priv);
var messageSign = Bitcoin.ECDSA.sign(messageHashBigInteger, key.priv);
var sighex = Crypto.util.bytesToHex(messageSign); var sighex = Crypto.util.bytesToHex(messageSign);
return sighex; return sighex;
}; }
//Verify signatue of the data using public-key //Verify signatue of the data using public-key
floCrypto.verifySign = function(data, signatureHex, publicKeyHex) { floCrypto.verifySign = function(data, signatureHex, publicKeyHex) {
var msgHash = Crypto.SHA256(data); var msgHash = Crypto.SHA256(data);
var messageHashBigInteger = new BigInteger(msgHash);
var sigBytes = Crypto.util.hexToBytes(signatureHex); var sigBytes = Crypto.util.hexToBytes(signatureHex);
var signature = Bitcoin.ECDSA.parseSig(sigBytes);
var publicKeyPoint = ecparams.getCurve().decodePointHex(publicKeyHex); var publicKeyPoint = ecparams.getCurve().decodePointHex(publicKeyHex);
var verify = Bitcoin.ECDSA.verifyRaw(messageHashBigInteger, var verify = Bitcoin.ECDSA.verify(msgHash, sigBytes, publicKeyPoint);
signature.r, signature.s, publicKeyPoint);
return verify; return verify;
}; }
//Generates a new flo ID and returns private-key, public-key and floID //Generates a new flo ID and returns private-key, public-key and floID
floCrypto.generateNewID = function() { const generateNewID = floCrypto.generateNewID = function() {
try {
var key = new Bitcoin.ECKey(false); var key = new Bitcoin.ECKey(false);
key.setCompressed(true); key.setCompressed(true);
return { return {
floID: key.getBitcoinAddress(), floID: key.getBitcoinAddress(),
pubKey: key.getPubKeyHex(), pubKey: key.getPubKeyHex(),
privKey: key.getBitcoinWalletImportFormat() privKey: key.getBitcoinWalletImportFormat()
}; }
} catch (e) { }
console.error(e);
}; Object.defineProperty(floCrypto, 'newID', {
}; get: () => generateNewID()
});
//Returns public-key from private-key //Returns public-key from private-key
floCrypto.getPubKeyHex = function(privateKeyHex) { floCrypto.getPubKeyHex = function(privateKeyHex) {
@ -182,7 +160,7 @@
return null; return null;
key.setCompressed(true); key.setCompressed(true);
return key.getPubKeyHex(); return key.getPubKeyHex();
}; }
//Returns flo-ID from public-key or private-key //Returns flo-ID from public-key or private-key
floCrypto.getFloID = function(keyHex) { floCrypto.getFloID = function(keyHex) {
@ -193,82 +171,173 @@
if (key.priv == null) if (key.priv == null)
key.setPub(keyHex); key.setPub(keyHex);
return key.getBitcoinAddress(); return key.getBitcoinAddress();
} catch (e) { } catch {
return null; return null;
}; }
}; }
//Verify the private-key for the given public-key or flo-ID //Verify the private-key for the given public-key or flo-ID
floCrypto.verifyPrivKey = function(privateKeyHex, publicHex_ID) { floCrypto.verifyPrivKey = function(privateKeyHex, pubKey_floID, isfloID = true) {
if (!privateKeyHex || !publicHex_ID) if (!privateKeyHex || !pubKey_floID)
return false; return false;
try { try {
var key = new Bitcoin.ECKey(privateKeyHex); var key = new Bitcoin.ECKey(privateKeyHex);
if (key.priv == null) if (key.priv == null)
return false; return false;
key.setCompressed(true); key.setCompressed(true);
if (publicHex_ID === key.getBitcoinAddress()) if (isfloID && pubKey_floID == key.getBitcoinAddress())
return true; return true;
else if (publicHex_ID === key.getPubKeyHex()) else if (!isfloID && pubKey_floID == key.getPubKeyHex())
return true; return true;
else else
return false; return false;
} catch (e) { } catch {
console.error(e); return null;
}; }
}; }
//Check if the given Address is valid or not //Check if the given flo-id is valid or not
floCrypto.validateAddr = function(inpAddr) { floCrypto.validateFloID = function(floID) {
if (!inpAddr) if (!floID)
return false; return false;
try { try {
var addr = new Bitcoin.Address(inpAddr); let addr = new Bitcoin.Address(floID);
return true; return true;
} catch { } catch {
return false; return false;
}; }
}; }
//Check if the given address (any blockchain) is valid or not
floCrypto.validateAddr = function(address, std = true, bech = false) {
if (address.length == 34) { //legacy or segwit encoding
if (std === false)
return false;
let decode = bitjs.Base58.decode(address);
var raw = decode.slice(0, decode.length - 4),
checksum = decode.slice(decode.length - 4);
var hash = Crypto.SHA256(Crypto.SHA256(raw, {
asBytes: true
}), {
asBytes: true
});
if (hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3])
return false;
else if (std === true || (!Array.isArray(std) && std === raw[0]) || (Array.isArray(std) && std.includes(raw[0])))
return true;
else
return false;
} else if (address.length == 42 || address.length == 62) { //bech encoding
if (bech === false)
return false;
else if (typeof btc_api !== "object")
throw "btc_api library missing (lib_btc.js)";
let decode = coinjs.bech32_decode(address);
if (!decode)
return false;
var raw = decode.data;
if (bech === true || (!Array.isArray(bech) && bech === raw[0]) || (Array.isArray(bech) && bech.includes(raw[0])))
return true;
else
return false;
} else //unknown length
return false;
}
//Split the str using shamir's Secret and Returns the shares //Split the str using shamir's Secret and Returns the shares
floCrypto.createShamirsSecretShares = function(str, total_shares, threshold_limit) { floCrypto.createShamirsSecretShares = function(str, total_shares, threshold_limit) {
try { try {
if (str.length > 0) { if (str.length > 0) {
var strHex = shamirSecretShare.str2hex(str); var strHex = shamirSecretShare.str2hex(str);
return shamirSecretShare.share(strHex, total_shares, threshold_limit); var shares = shamirSecretShare.share(strHex, total_shares, threshold_limit);
}; return shares;
}
return false;
} catch {
return false
}
}
//Returns the retrived secret by combining the shamirs shares
const retrieveShamirSecret = floCrypto.retrieveShamirSecret = function(sharesArray) {
try {
if (sharesArray.length > 0) {
var comb = shamirSecretShare.combine(sharesArray.slice(0, sharesArray.length));
comb = shamirSecretShare.hex2str(comb);
return comb;
}
return false; return false;
} catch { } catch {
return false; return false;
}; }
}; }
//Verifies the shares and str //Verifies the shares and str
floCrypto.verifyShamirsSecret = function(sharesArray, str) { floCrypto.verifyShamirsSecret = function(sharesArray, str) {
if(str == false) if (!str)
return null;
else if (retrieveShamirSecret(sharesArray) === str)
return true;
else
return false; return false;
try { }
if (sharesArray.length > 0) {
var comb = shamirSecretShare.combine(sharesArray.slice(0, sharesArray.length));
return (shamirSecretShare.hex2str(comb) === str ? true : false);
};
return false;
} catch {
return false;
};
};
//Returns the retrived secret by combining the shamirs shares const validateASCII = floCrypto.validateASCII = function(string, bool = true) {
floCrypto.retrieveShamirSecret = function(sharesArray) { if (typeof string !== "string")
try { return null;
if (sharesArray.length > 0) { if (bool) {
var comb = shamirSecretShare.combine(sharesArray.slice(0, sharesArray.length)); let x;
return shamirSecretShare.hex2str(comb); for (let i = 0; i < string.length; i++) {
}; x = string.charCodeAt(i);
if (x < 32 || x > 127)
return false; return false;
} catch { }
return false; return true;
}; } else {
}; let x, invalids = {};
for (let i = 0; i < string.length; i++) {
x = string.charCodeAt(i);
if (x < 32 || x > 127)
if (x in invalids)
invalids[string[i]].push(i)
else
invalids[string[i]] = [i];
}
if (Object.keys(invalids).length)
return invalids;
else
return true;
}
}
})(typeof global !== "undefined" ? global : window); floCrypto.convertToASCII = function(string, mode = 'soft-remove') {
let chars = validateASCII(string, false);
if (chars === true)
return string;
else if (chars === null)
return null;
let convertor, result = string,
refAlt = {};
ascii_alternatives.split('\n').forEach(a => refAlt[a[0]] = a.slice(2));
mode = mode.toLowerCase();
if (mode === "hard-unicode")
convertor = (c) => `\\u${('000'+c.charCodeAt().toString(16)).slice(-4)}`;
else if (mode === "soft-unicode")
convertor = (c) => refAlt[c] || `\\u${('000'+c.charCodeAt().toString(16)).slice(-4)}`;
else if (mode === "hard-remove")
convertor = c => "";
else if (mode === "soft-remove")
convertor = c => refAlt[c] || "";
else
return null;
for (let c in chars)
result = result.replaceAll(c, convertor(c));
return result;
}
floCrypto.revertUnicode = function(string) {
return string.replace(/\\u[\dA-F]{4}/gi,
m => String.fromCharCode(parseInt(m.replace(/\\u/g, ''), 16)));
}
})('object' === typeof module ? module.exports : window.floCrypto = {});

View File

@ -3,14 +3,7 @@ const floGlobals = {
//Required for all //Required for all
blockchain: "FLO", blockchain: "FLO",
//Required for blockchain API operators
apiURL: {
FLO: ['https://explorer.mediciland.com/', 'https://livenet.flocha.in/', 'https://flosight.duckdns.org/', 'http://livenet-explorer.floexperiments.com'],
FLO_TEST: ['https://testnet-flosight.duckdns.org', 'https://testnet.flocha.in/']
},
SNStorageID: "FNaN9McoBAEFUjkRmNQRYLmBF8SpS7Tgfk", SNStorageID: "FNaN9McoBAEFUjkRmNQRYLmBF8SpS7Tgfk",
//sendAmt: 0.001,
//fee: 0.0005,
//Required for Supernode operations //Required for Supernode operations
supernodes: {}, //each supnernode must be stored as floID : {uri:<uri>,pubKey:<publicKey>} supernodes: {}, //each supnernode must be stored as floID : {uri:<uri>,pubKey:<publicKey>}

View File

@ -1,5 +1,4 @@
'use strict'; 'use strict';
require('./lib/BuildKBucket');
module.exports = function K_Bucket(options = {}) { module.exports = function K_Bucket(options = {}) {

View File

@ -1,6 +1,13 @@
(function(GLOBAL) { //lib v1.2.3
'use strict'; 'use strict';
/* Utility Libraries required for Standard operations
* All credits for these codes belong to their respective creators, moderators and owners.
* For more info (including license and terms of use), please visit respective source.
*/
GLOBAL.cryptocoin = (typeof floGlobals === 'undefined' ? null : floGlobals.blockchain) || 'FLO';
//Crypto.js //Crypto.js
(function(GLOBAL) { (function() {
// Global Crypto object // Global Crypto object
var Crypto = GLOBAL.Crypto = {}; var Crypto = GLOBAL.Crypto = {};
/*! /*!
@ -393,17 +400,21 @@
return g && g.asBytes ? c : g && g.asString ? a.bytesToString(c) : k.bytesToHex(c) return g && g.asBytes ? c : g && g.asString ? a.bytesToString(c) : k.bytesToHex(c)
} }
})(); })();
})(typeof global !== "undefined" ? global : window); })();
//SecureRandom.js //SecureRandom.js
(function(GLOBAL) { (function() {
var getRandomValues = const getRandomValues = function(buf) {
(typeof require === 'function') ? function(buf) { if (typeof require === 'function') {
var bytes = require('crypto').randomBytes(buf.length) var bytes = require('crypto').randomBytes(buf.length);
buf.set(bytes) buf.set(bytes)
return buf; return buf;
} : (GLOBAL.crypto && GLOBAL.crypto.getRandomValues ? GLOBAL.crypto.getRandomValues : null); } else if (GLOBAL.crypto && GLOBAL.crypto.getRandomValues)
return GLOBAL.crypto.getRandomValues(buf);
else
return null;
}
/*! /*!
* Random number generator with ArcFour PRNG * Random number generator with ArcFour PRNG
@ -593,10 +604,10 @@
sr.seedInt8(entropyBytes[i]); sr.seedInt8(entropyBytes[i]);
} }
} }
})(typeof global !== "undefined" ? global : window); })();
//ripemd160.js //ripemd160.js
(function(GLOBAL) { (function() {
/* /*
CryptoJS v3.1.2 CryptoJS v3.1.2
@ -794,10 +805,10 @@
var digestbytes = wordsToBytes(H); var digestbytes = wordsToBytes(H);
return digestbytes; return digestbytes;
} }
})(typeof global !== "undefined" ? global : window); })();
//BigInteger.js //BigInteger.js
(function(GLOBAL) { (function() {
// Upstream 'BigInteger' here: // Upstream 'BigInteger' here:
// Original Author: http://www-cs-students.stanford.edu/~tjw/jsbn/ // Original Author: http://www-cs-students.stanford.edu/~tjw/jsbn/
// Follows 'jsbn' on Github: https://github.com/jasondavies/jsbn // Follows 'jsbn' on Github: https://github.com/jasondavies/jsbn
@ -2360,10 +2371,10 @@
// int hashCode() // int hashCode()
// long longValue() // long longValue()
// static BigInteger valueOf(long val) // static BigInteger valueOf(long val)
})(typeof global !== "undefined" ? global : window); })();
//ellipticcurve.js //ellipticcurve.js
(function(GLOBAL) { (function() {
/*! /*!
* Basic Javascript Elliptic Curve implementation * Basic Javascript Elliptic Curve implementation
* Ported loosely from BouncyCastle's Java EC code * Ported loosely from BouncyCastle's Java EC code
@ -4310,10 +4321,10 @@
if (ec.secNamedCurves[name] == undefined) return null; if (ec.secNamedCurves[name] == undefined) return null;
return ec.secNamedCurves[name](); return ec.secNamedCurves[name]();
} }
})(typeof global !== "undefined" ? global : window); })();
//bitTrx.js //bitTrx.js
(function(GLOBAL) { (function() {
var bitjs = GLOBAL.bitjs = function() {}; var bitjs = GLOBAL.bitjs = function() {};
@ -4761,9 +4772,9 @@
} }
buffer = buffer.concat(bitjs.numToBytes(parseInt(this.locktime), 4)); buffer = buffer.concat(bitjs.numToBytes(parseInt(this.locktime), 4));
flohex = ascii_to_hexa(this.floData); var flohex = ascii_to_hexa(this.floData);
floDataCount = this.floData.length; var floDataCount = this.floData.length;
var floDataCountString;
//flochange -- creating unique data character count logic for floData. This string is prefixed before actual floData string in Raw Transaction //flochange -- creating unique data character count logic for floData. This string is prefixed before actual floData string in Raw Transaction
if (floDataCount < 16) { if (floDataCount < 16) {
floDataCountString = floDataCount.toString(16); floDataCountString = floDataCount.toString(16);
@ -4904,10 +4915,10 @@
} }
return bitjs; return bitjs;
})(typeof global !== "undefined" ? global : window); })();
//Bitcoin.js //Bitcoin.js
(function(GLOBAL) { (function() {
/* /*
Copyright (c) 2011 Stefan Thomas Copyright (c) 2011 Stefan Thomas
@ -5005,12 +5016,12 @@
* *
* Returns the address as a base58-encoded string in the standardized format. * Returns the address as a base58-encoded string in the standardized format.
*/ */
Bitcoin.Address.prototype.toString = function() { Bitcoin.Address.prototype.toString = function(version = null) {
// Get a copy of the hash // Get a copy of the hash
var hash = this.hash.slice(0); var hash = this.hash.slice(0);
// Version // Version
hash.unshift(this.version); hash.unshift(version !== null ? version : this.version);
var checksum = Crypto.SHA256(Crypto.SHA256(hash, { var checksum = Crypto.SHA256(Crypto.SHA256(hash, {
asBytes: true asBytes: true
}), { }), {
@ -5119,7 +5130,7 @@
} }
var Q; var Q;
if (pubkey instanceof ec.PointFp) { if (pubkey instanceof EllipticCurve.PointFp) {
Q = pubkey; Q = pubkey;
} else if (Bitcoin.Util.isArray(pubkey)) { } else if (Bitcoin.Util.isArray(pubkey)) {
Q = EllipticCurve.PointFp.decodeFrom(ecparams.getCurve(), pubkey); Q = EllipticCurve.PointFp.decodeFrom(ecparams.getCurve(), pubkey);
@ -5433,9 +5444,8 @@
var bytes = null; var bytes = null;
try { try {
// This part is edited for FLO. FLO WIF are always compressed WIF. FLO WIF (private key) starts with R for mainnet and c for testnet. // This part is edited for FLO. FLO WIF are always compressed WIF (length of 52).
if (((GLOBAL.cryptocoin == "FLO") && /^R[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(input)) || if ((/^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{52}$/.test(input))) {
((GLOBAL.cryptocoin == "FLO_TEST") && /^c[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(input))) {
bytes = ECKey.decodeCompressedWalletImportFormat(input); bytes = ECKey.decodeCompressedWalletImportFormat(input);
this.compressed = true; this.compressed = true;
} else if (ECKey.isHexFormat(input)) { } else if (ECKey.isHexFormat(input)) {
@ -5662,9 +5672,11 @@
} }
var version = hash.shift(); var version = hash.shift();
/*
if (version != ECKey.privateKeyPrefix) { if (version != ECKey.privateKeyPrefix) {
throw "Version " + version + " not supported!"; throw "Version " + version + " not supported!";
} }
*/
return hash; return hash;
}; };
@ -5686,9 +5698,11 @@
throw "Checksum validation failed!"; throw "Checksum validation failed!";
} }
var version = hash.shift(); var version = hash.shift();
/*
if (version != ECKey.privateKeyPrefix) { if (version != ECKey.privateKeyPrefix) {
throw "Version " + version + " not supported!"; throw "Version " + version + " not supported!";
} }
*/
hash.pop(); hash.pop();
return hash; return hash;
}; };
@ -5866,10 +5880,10 @@
return true; return true;
} }
}; };
})(typeof global !== "undefined" ? global : window); })();
//ellipticCurveEncryption.js //ellipticCurveEncryption.js
(function(GLOBAL) { (function() {
(function(ellipticCurveType) { (function(ellipticCurveType) {
//Defining Elliptic Encryption Object //Defining Elliptic Encryption Object
@ -6001,10 +6015,10 @@
} }
})("secp256k1"); })("secp256k1");
})(typeof global !== "undefined" ? global : window); })();
//secrets.js //secrets.js
(function(GLOBAL) { (function() {
//Shamir Secret Share by Alexander Stetsyuk - released under MIT License //Shamir Secret Share by Alexander Stetsyuk - released under MIT License
var SecretShare = GLOBAL.shamirSecretShare = {}; var SecretShare = GLOBAL.shamirSecretShare = {};
@ -6116,8 +6130,7 @@
} }
// browsers with window.crypto.getRandomValues() // browsers with window.crypto.getRandomValues()
if (GLOBAL['crypto'] && typeof GLOBAL['crypto']['getRandomValues'] === 'function' && typeof GLOBAL[ if (GLOBAL['crypto'] && typeof GLOBAL['crypto']['getRandomValues'] === 'function' && typeof GLOBAL['Uint32Array'] === 'function') {
'Uint32Array'] === 'function') {
crypto = GLOBAL['crypto']; crypto = GLOBAL['crypto'];
return function(bits) { return function(bits) {
var elems = Math.ceil(bits / 32), var elems = Math.ceil(bits / 32),
@ -6575,4 +6588,203 @@
// by default, initialize without an RNG // by default, initialize without an RNG
SecretShare.init(); SecretShare.init();
})(typeof global !== 'undefined' ? global : window); })();
//kbucket.js
(function() {
const getRandomValues = function(buf) {
if (typeof require === 'function') {
var bytes = require('crypto').randomBytes(buf.length);
buf.set(bytes)
return buf;
} else if (GLOBAL.crypto && GLOBAL.crypto.getRandomValues)
return GLOBAL.crypto.getRandomValues(buf);
else
return null;
}
// Kademlia DHT K-bucket implementation as a binary tree.
// by 'Tristan Slominski' under 'MIT License'
GLOBAL.BuildKBucket = function KBucket(options = {}) {
if (!(this instanceof KBucket))
return new KBucket(options);
this.localNodeId = options.localNodeId || getRandomValues(new Uint8Array(20))
this.numberOfNodesPerKBucket = options.numberOfNodesPerKBucket || 20
this.numberOfNodesToPing = options.numberOfNodesToPing || 3
this.distance = options.distance || this.distance
this.arbiter = options.arbiter || this.arbiter
this.metadata = Object.assign({}, options.metadata)
this.createNode = function() {
return {
contacts: [],
dontSplit: false,
left: null,
right: null
}
}
this.ensureInt8 = function(name, val) {
if (!(val instanceof Uint8Array))
throw new TypeError(name + ' is not a Uint8Array')
}
this.arrayEquals = function(array1, array2) {
if (array1 === array2)
return true
if (array1.length !== array2.length)
return false
for (let i = 0, length = array1.length; i < length; ++i)
if (array1[i] !== array2[i])
return false
return true
}
this.ensureInt8('option.localNodeId as parameter 1', this.localNodeId)
this.root = this.createNode()
this.arbiter = function(incumbent, candidate) {
return incumbent.vectorClock > candidate.vectorClock ? incumbent : candidate
}
this.distance = function(firstId, secondId) {
let distance = 0
let i = 0
const min = Math.min(firstId.length, secondId.length)
const max = Math.max(firstId.length, secondId.length)
for (; i < min; ++i)
distance = distance * 256 + (firstId[i] ^ secondId[i])
for (; i < max; ++i) distance = distance * 256 + 255
return distance
}
this.add = function(contact) {
this.ensureInt8('contact.id', (contact || {}).id)
let bitIndex = 0
let node = this.root
while (node.contacts === null)
node = this._determineNode(node, contact.id, bitIndex++)
const index = this._indexOf(node, contact.id)
if (index >= 0) {
this._update(node, index, contact)
return this
}
if (node.contacts.length < this.numberOfNodesPerKBucket) {
node.contacts.push(contact)
return this
}
if (node.dontSplit)
return this
this._split(node, bitIndex)
return this.add(contact)
}
this.closest = function(id, n = Infinity) {
this.ensureInt8('id', id)
if ((!Number.isInteger(n) && n !== Infinity) || n <= 0)
throw new TypeError('n is not positive number')
let contacts = []
for (let nodes = [this.root], bitIndex = 0; nodes.length > 0 && contacts.length < n;) {
const node = nodes.pop()
if (node.contacts === null) {
const detNode = this._determineNode(node, id, bitIndex++)
nodes.push(node.left === detNode ? node.right : node.left)
nodes.push(detNode)
} else
contacts = contacts.concat(node.contacts)
}
return contacts
.map(a => [this.distance(a.id, id), a])
.sort((a, b) => a[0] - b[0])
.slice(0, n)
.map(a => a[1])
}
this.count = function() {
let count = 0
for (const nodes = [this.root]; nodes.length > 0;) {
const node = nodes.pop()
if (node.contacts === null)
nodes.push(node.right, node.left)
else
count += node.contacts.length
}
return count
}
this._determineNode = function(node, id, bitIndex) {
const bytesDescribedByBitIndex = bitIndex >> 3
const bitIndexWithinByte = bitIndex % 8
if ((id.length <= bytesDescribedByBitIndex) && (bitIndexWithinByte !== 0))
return node.left
const byteUnderConsideration = id[bytesDescribedByBitIndex]
if (byteUnderConsideration & (1 << (7 - bitIndexWithinByte)))
return node.right
return node.left
}
this.get = function(id) {
this.ensureInt8('id', id)
let bitIndex = 0
let node = this.root
while (node.contacts === null)
node = this._determineNode(node, id, bitIndex++)
const index = this._indexOf(node, id)
return index >= 0 ? node.contacts[index] : null
}
this._indexOf = function(node, id) {
for (let i = 0; i < node.contacts.length; ++i)
if (this.arrayEquals(node.contacts[i].id, id))
return i
return -1
}
this.remove = function(id) {
this.ensureInt8('the id as parameter 1', id)
let bitIndex = 0
let node = this.root
while (node.contacts === null)
node = this._determineNode(node, id, bitIndex++)
const index = this._indexOf(node, id)
if (index >= 0)
node.contacts.splice(index, 1)[0]
return this
}
this._split = function(node, bitIndex) {
node.left = this.createNode()
node.right = this.createNode()
for (const contact of node.contacts)
this._determineNode(node, contact.id, bitIndex).contacts.push(contact)
node.contacts = null
const detNode = this._determineNode(node, this.localNodeId, bitIndex)
const otherNode = node.left === detNode ? node.right : node.left
otherNode.dontSplit = true
}
this.toArray = function() {
let result = []
for (const nodes = [this.root]; nodes.length > 0;) {
const node = nodes.pop()
if (node.contacts === null)
nodes.push(node.right, node.left)
else
result = result.concat(node.contacts)
}
return result
}
this._update = function(node, index, contact) {
if (!this.arrayEquals(node.contacts[index].id, contact.id))
throw new Error('wrong index for _update')
const incumbent = node.contacts[index]
const selection = this.arbiter(incumbent, contact)
if (selection === incumbent && incumbent !== contact) return
node.contacts.splice(index, 1)
node.contacts.push(selection)
}
}
})();
})(typeof global !== "undefined" ? global : window);

View File

@ -1,405 +0,0 @@
'use strict';
/*Kademlia DHT K-bucket implementation as a binary tree.*/
(function(GLOBAL) {
/**
* Implementation of a Kademlia DHT k-bucket used for storing
* contact (peer node) information.
*
* @extends EventEmitter
*/
GLOBAL.BuildKBucket = function BuildKBucket(options = {}) {
/**
* `options`:
* `distance`: Function
* `function (firstId, secondId) { return distance }` An optional
* `distance` function that gets two `id` Uint8Arrays
* and return distance (as number) between them.
* `arbiter`: Function (Default: vectorClock arbiter)
* `function (incumbent, candidate) { return contact; }` An optional
* `arbiter` function that givent two `contact` objects with the same `id`
* returns the desired object to be used for updating the k-bucket. For
* more details, see [arbiter function](#arbiter-function).
* `localNodeId`: Uint8Array An optional Uint8Array representing the local node id.
* If not provided, a local node id will be created via `randomBytes(20)`.
* `metadata`: Object (Default: {}) Optional satellite data to include
* with the k-bucket. `metadata` property is guaranteed not be altered by,
* it is provided as an explicit container for users of k-bucket to store
* implementation-specific data.
* `numberOfNodesPerKBucket`: Integer (Default: 20) The number of nodes
* that a k-bucket can contain before being full or split.
* `numberOfNodesToPing`: Integer (Default: 3) The number of nodes to
* ping when a bucket that should not be split becomes full. KBucket will
* emit a `ping` event that contains `numberOfNodesToPing` nodes that have
* not been contacted the longest.
*
* @param {Object=} options optional
*/
this.localNodeId = options.localNodeId || window.crypto.getRandomValues(new Uint8Array(20))
this.numberOfNodesPerKBucket = options.numberOfNodesPerKBucket || 20
this.numberOfNodesToPing = options.numberOfNodesToPing || 3
this.distance = options.distance || this.distance
// use an arbiter from options or vectorClock arbiter by default
this.arbiter = options.arbiter || this.arbiter
this.metadata = Object.assign({}, options.metadata)
this.createNode = function() {
return {
contacts: [],
dontSplit: false,
left: null,
right: null
}
}
this.ensureInt8 = function(name, val) {
if (!(val instanceof Uint8Array)) {
throw new TypeError(name + ' is not a Uint8Array')
}
}
/**
* @param {Uint8Array} array1
* @param {Uint8Array} array2
* @return {Boolean}
*/
this.arrayEquals = function(array1, array2) {
if (array1 === array2) {
return true
}
if (array1.length !== array2.length) {
return false
}
for (let i = 0, length = array1.length; i < length; ++i) {
if (array1[i] !== array2[i]) {
return false
}
}
return true
}
this.ensureInt8('option.localNodeId as parameter 1', this.localNodeId)
this.root = this.createNode()
/**
* Default arbiter function for contacts with the same id. Uses
* contact.vectorClock to select which contact to update the k-bucket with.
* Contact with larger vectorClock field will be selected. If vectorClock is
* the same, candidat will be selected.
*
* @param {Object} incumbent Contact currently stored in the k-bucket.
* @param {Object} candidate Contact being added to the k-bucket.
* @return {Object} Contact to updated the k-bucket with.
*/
this.arbiter = function(incumbent, candidate) {
return incumbent.vectorClock > candidate.vectorClock ? incumbent : candidate
}
/**
* Default distance function. Finds the XOR
* distance between firstId and secondId.
*
* @param {Uint8Array} firstId Uint8Array containing first id.
* @param {Uint8Array} secondId Uint8Array containing second id.
* @return {Number} Integer The XOR distance between firstId
* and secondId.
*/
this.distance = function(firstId, secondId) {
let distance = 0
let i = 0
const min = Math.min(firstId.length, secondId.length)
const max = Math.max(firstId.length, secondId.length)
for (; i < min; ++i) {
distance = distance * 256 + (firstId[i] ^ secondId[i])
}
for (; i < max; ++i) distance = distance * 256 + 255
return distance
}
/**
* Adds a contact to the k-bucket.
*
* @param {Object} contact the contact object to add
*/
this.add = function(contact) {
this.ensureInt8('contact.id', (contact || {}).id)
let bitIndex = 0
let node = this.root
while (node.contacts === null) {
// this is not a leaf node but an inner node with 'low' and 'high'
// branches; we will check the appropriate bit of the identifier and
// delegate to the appropriate node for further processing
node = this._determineNode(node, contact.id, bitIndex++)
}
// check if the contact already exists
const index = this._indexOf(node, contact.id)
if (index >= 0) {
this._update(node, index, contact)
return this
}
if (node.contacts.length < this.numberOfNodesPerKBucket) {
node.contacts.push(contact)
return this
}
// the bucket is full
if (node.dontSplit) {
// we are not allowed to split the bucket
// we need to ping the first this.numberOfNodesToPing
// in order to determine if they are alive
// only if one of the pinged nodes does not respond, can the new contact
// be added (this prevents DoS flodding with new invalid contacts)
return this
}
this._split(node, bitIndex)
return this.add(contact)
}
/**
* Get the n closest contacts to the provided node id. "Closest" here means:
* closest according to the XOR metric of the contact node id.
*
* @param {Uint8Array} id Contact node id
* @param {Number=} n Integer (Default: Infinity) The maximum number of
* closest contacts to return
* @return {Array} Array Maximum of n closest contacts to the node id
*/
this.closest = function(id, n = Infinity) {
this.ensureInt8('id', id)
if ((!Number.isInteger(n) && n !== Infinity) || n <= 0) {
throw new TypeError('n is not positive number')
}
let contacts = []
for (let nodes = [this.root], bitIndex = 0; nodes.length > 0 && contacts.length < n;) {
const node = nodes.pop()
if (node.contacts === null) {
const detNode = this._determineNode(node, id, bitIndex++)
nodes.push(node.left === detNode ? node.right : node.left)
nodes.push(detNode)
} else {
contacts = contacts.concat(node.contacts)
}
}
return contacts
.map(a => [this.distance(a.id, id), a])
.sort((a, b) => a[0] - b[0])
.slice(0, n)
.map(a => a[1])
}
/**
* Counts the total number of contacts in the tree.
*
* @return {Number} The number of contacts held in the tree
*/
this.count = function() {
// return this.toArray().length
let count = 0
for (const nodes = [this.root]; nodes.length > 0;) {
const node = nodes.pop()
if (node.contacts === null) nodes.push(node.right, node.left)
else count += node.contacts.length
}
return count
}
/**
* Determines whether the id at the bitIndex is 0 or 1.
* Return left leaf if `id` at `bitIndex` is 0, right leaf otherwise
*
* @param {Object} node internal object that has 2 leafs: left and right
* @param {Uint8Array} id Id to compare localNodeId with.
* @param {Number} bitIndex Integer (Default: 0) The bit index to which bit
* to check in the id Uint8Array.
* @return {Object} left leaf if id at bitIndex is 0, right leaf otherwise.
*/
this._determineNode = function(node, id, bitIndex) {
// *NOTE* remember that id is a Uint8Array and has granularity of
// bytes (8 bits), whereas the bitIndex is the bit index (not byte)
// id's that are too short are put in low bucket (1 byte = 8 bits)
// (bitIndex >> 3) finds how many bytes the bitIndex describes
// bitIndex % 8 checks if we have extra bits beyond byte multiples
// if number of bytes is <= no. of bytes described by bitIndex and there
// are extra bits to consider, this means id has less bits than what
// bitIndex describes, id therefore is too short, and will be put in low
// bucket
const bytesDescribedByBitIndex = bitIndex >> 3
const bitIndexWithinByte = bitIndex % 8
if ((id.length <= bytesDescribedByBitIndex) && (bitIndexWithinByte !== 0)) {
return node.left
}
const byteUnderConsideration = id[bytesDescribedByBitIndex]
// byteUnderConsideration is an integer from 0 to 255 represented by 8 bits
// where 255 is 11111111 and 0 is 00000000
// in order to find out whether the bit at bitIndexWithinByte is set
// we construct (1 << (7 - bitIndexWithinByte)) which will consist
// of all bits being 0, with only one bit set to 1
// for example, if bitIndexWithinByte is 3, we will construct 00010000 by
// (1 << (7 - 3)) -> (1 << 4) -> 16
if (byteUnderConsideration & (1 << (7 - bitIndexWithinByte))) {
return node.right
}
return node.left
}
/**
* Get a contact by its exact ID.
* If this is a leaf, loop through the bucket contents and return the correct
* contact if we have it or null if not. If this is an inner node, determine
* which branch of the tree to traverse and repeat.
*
* @param {Uint8Array} id The ID of the contact to fetch.
* @return {Object|Null} The contact if available, otherwise null
*/
this.get = function(id) {
this.ensureInt8('id', id)
let bitIndex = 0
let node = this.root
while (node.contacts === null) {
node = this._determineNode(node, id, bitIndex++)
}
// index of uses contact id for matching
const index = this._indexOf(node, id)
return index >= 0 ? node.contacts[index] : null
}
/**
* Returns the index of the contact with provided
* id if it exists, returns -1 otherwise.
*
* @param {Object} node internal object that has 2 leafs: left and right
* @param {Uint8Array} id Contact node id.
* @return {Number} Integer Index of contact with provided id if it
* exists, -1 otherwise.
*/
this._indexOf = function(node, id) {
for (let i = 0; i < node.contacts.length; ++i) {
if (this.arrayEquals(node.contacts[i].id, id)) return i
}
return -1
}
/**
* Removes contact with the provided id.
*
* @param {Uint8Array} id The ID of the contact to remove.
* @return {Object} The k-bucket itself.
*/
this.remove = function(id) {
this.ensureInt8('the id as parameter 1', id)
let bitIndex = 0
let node = this.root
while (node.contacts === null) {
node = this._determineNode(node, id, bitIndex++)
}
const index = this._indexOf(node, id)
if (index >= 0) {
const contact = node.contacts.splice(index, 1)[0]
}
return this
}
/**
* Splits the node, redistributes contacts to the new nodes, and marks the
* node that was split as an inner node of the binary tree of nodes by
* setting this.root.contacts = null
*
* @param {Object} node node for splitting
* @param {Number} bitIndex the bitIndex to which byte to check in the
* Uint8Array for navigating the binary tree
*/
this._split = function(node, bitIndex) {
node.left = this.createNode()
node.right = this.createNode()
// redistribute existing contacts amongst the two newly created nodes
for (const contact of node.contacts) {
this._determineNode(node, contact.id, bitIndex).contacts.push(contact)
}
node.contacts = null // mark as inner tree node
// don't split the "far away" node
// we check where the local node would end up and mark the other one as
// "dontSplit" (i.e. "far away")
const detNode = this._determineNode(node, this.localNodeId, bitIndex)
const otherNode = node.left === detNode ? node.right : node.left
otherNode.dontSplit = true
}
/**
* Returns all the contacts contained in the tree as an array.
* If this is a leaf, return a copy of the bucket. `slice` is used so that we
* don't accidentally leak an internal reference out that might be
* accidentally misused. If this is not a leaf, return the union of the low
* and high branches (themselves also as arrays).
*
* @return {Array} All of the contacts in the tree, as an array
*/
this.toArray = function() {
let result = []
for (const nodes = [this.root]; nodes.length > 0;) {
const node = nodes.pop()
if (node.contacts === null) nodes.push(node.right, node.left)
else result = result.concat(node.contacts)
}
return result
}
/**
* Updates the contact selected by the arbiter.
* If the selection is our old contact and the candidate is some new contact
* then the new contact is abandoned (not added).
* If the selection is our old contact and the candidate is our old contact
* then we are refreshing the contact and it is marked as most recently
* contacted (by being moved to the right/end of the bucket array).
* If the selection is our new contact, the old contact is removed and the new
* contact is marked as most recently contacted.
*
* @param {Object} node internal object that has 2 leafs: left and right
* @param {Number} index the index in the bucket where contact exists
* (index has already been computed in a previous
* calculation)
* @param {Object} contact The contact object to update.
*/
this._update = function(node, index, contact) {
// sanity check
if (!this.arrayEquals(node.contacts[index].id, contact.id)) {
throw new Error('wrong index for _update')
}
const incumbent = node.contacts[index]
const selection = this.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
node.contacts.splice(index, 1) // remove old contact
node.contacts.push(selection) // add more recent contact version
}
}
})(typeof global !== "undefined" ? global : window)

View File

@ -3,8 +3,8 @@ global.floGlobals = require("./floGlobals");
require('./set_globals'); require('./set_globals');
require('./lib'); require('./lib');
const K_Bucket = require('./kBucket'); const K_Bucket = require('./kBucket');
require('./floCrypto'); global.floCrypto = require('./floCrypto');
require('./floBlockchainAPI'); global.floBlockchainAPI = require('./floBlockchainAPI');
const Database = require("./database"); const Database = require("./database");
const intra = require('./intra'); const intra = require('./intra');
const client = require('./client'); const client = require('./client');