Compare commits

..

25 Commits

Author SHA1 Message Date
4183950136
Udating encoding/decoding to modern standards
1.Using TextEncoder for new encoding,and TextDecoder for decoding
2. Dual decoding in case the modern decoder fails, then retry with older decoder.
2025-08-28 12:46:19 +05:30
f228efb855
Exposing floBlockchainAPI.apiURL 2025-08-26 09:41:19 +05:30
3750d98038
Update floDapps.js
Improving offline capabilities. Will not get hung if cloud supernodes are offline
2025-08-25 07:52:11 +05:30
032acc341d
Update floCloudAPI.js
Improving offline error capabilities
2025-08-25 07:50:02 +05:30
416edd0b9c
Update floTokenAPI.js
Fixing crash when zero token balance existed
2025-08-23 14:14:06 +05:30
Sai Raj
be77021a95 floTokenAPI v1.2.1a
bug fix for token balance api
2024-08-14 22:34:38 -04:00
Sai Raj
3fef7f222e floTokenAPI v1.2.1: bug fix for token API update 2024-08-04 23:22:29 -04:00
sairaj mote
3ef1be2958 shifting to torproject tor detection api 2024-01-27 21:37:00 +05:30
sairaj mote
f108f91693 shifting to new tor link 2024-01-21 00:57:50 +05:30
sairaj mote
ed301f9661 adding different tor detection 2024-01-16 13:55:48 +05:30
sairaj mote
7757ac3239 Adding tor API support 2024-01-09 03:32:50 +05:30
sairaj mote
7a99b45b42 code refactoring 2024-01-05 02:56:21 +05:30
sairaj mote
542b9be9ca adding multi API support 2024-01-03 22:51:06 +05:30
sairaj mote
6727d369ca Revert "adding multi API support"
This reverts commit 3c7f473057.
2023-12-29 04:26:48 +05:30
sairaj mote
3c7f473057 adding multi API support 2023-12-28 02:14:15 +05:30
sairaj mote
19ffa601f1 Update index.html 2023-10-25 21:27:38 +05:30
Vivek Teega
2ac32bf360
Update floBlockchainAPI.js 2023-10-06 14:07:01 +05:30
0b547f73e9
Update btcOperator.js
Added Taproot Changes
Added support for Multisig fee Editing
Exposed internal functions under btcOperator object
2023-09-30 14:07:02 +05:30
sairajzero
098a62047c floCloudAPI v2.4.5 : file support
- uploadFile: upload a file to the cloud
- downloadFile: download a file from cloud

- upload/download file supports encryption of file. use options.encrypt in uploadFile and options.decrypt in downloadFile
2023-07-29 05:41:06 +05:30
sairajzero
5be35c28ce floDapps v2.4.1
- support for multiple cloud networks
2023-07-29 05:01:14 +05:30
sairajzero
471f291848 floCloudAPI v2.4.4: edit comment feature
- senders can now edit the comment of data they sent (by re-signing the new data)
2023-07-26 03:45:35 +05:30
sairajzero
904deaa63c floBlockchainAPI v3.0.1b - bug fix
- Fixed: vin address at .addresses[0] not .scriptSig.addresses[0]
2023-07-05 13:48:38 +05:30
sairajzero
e120b657da floBlockchainAPI v3.0.1a
- Fixed: readTx and all its dependencies not having txs property when address (floID) doesnt have any tx
2023-07-05 13:35:07 +05:30
sairajzero
5398fcbbbc floBlockchainAPI v3.0.1
- Fixed readTxs: not working
- Removed fromBlock and toBlock options from readTxs

- Fixed: chain querying to blockbook format for readAllTxs, readData, getLatestData

- Changed `mempool` option to `confirmed` option (for blockbook API)
- Removed `before` options from respective fns
2023-07-05 05:14:44 +05:30
sairajzero
d15af05764 floBlockchainAPI v3.0.0: BlockBook API
- Converting API calls to FLO blockbook API
- Changes and fixes required for the same
2023-07-04 00:20:24 +05:30
14 changed files with 1380 additions and 570 deletions

File diff suppressed because it is too large Load Diff

1
btcOperator.min.js vendored Normal file

File diff suppressed because one or more lines are too long

1
compactIDB.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -1,13 +1,13 @@
(function (EXPORTS) { //floBlockchainAPI v2.5.6b (function (EXPORTS) { //floBlockchainAPI v3.1.4
/* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ /* FLO Blockchain Operator to send/receive data from blockchain using API calls via FLO Blockbook*/
'use strict'; 'use strict';
const floBlockchainAPI = EXPORTS; const floBlockchainAPI = EXPORTS;
const DEFAULT = { const DEFAULT = {
blockchain: floGlobals.blockchain, blockchain: floGlobals.blockchain,
apiURL: { apiURL: {
FLO: ['https://flosight.ranchimall.net/'], FLO: ['https://blockbook.ranchimall.net/'],
FLO_TEST: ['https://flosight-testnet.ranchimall.net/'] FLO_TEST: ['https://blockbook-testnet.ranchimall.net/']
}, },
sendAmt: 0.0003, sendAmt: 0.0003,
fee: 0.0002, fee: 0.0002,
@ -15,9 +15,29 @@
receiverID: floGlobals.adminID receiverID: floGlobals.adminID
}; };
floBlockchainAPI.apiURL = DEFAULT.apiURL[DEFAULT.blockchain][0];
const SATOSHI_IN_BTC = 1e8; const SATOSHI_IN_BTC = 1e8;
const isUndefined = val => typeof val === 'undefined'; const isUndefined = val => typeof val === 'undefined';
const checkIfTor = floBlockchainAPI.checkIfTor = () => {
return fetch('https://check.torproject.org/api/ip')
.then(res => res.json())
.then(res => {
return res.IsTor
}).catch(e => {
console.error(e)
return false
})
}
let isTor = false;
checkIfTor().then(result => {
isTor = result
if (isTor) {
DEFAULT.apiURL.FLO.push('http://xge4kejxl6xs4cad3u3a7dnw7idndlkn3vmyo33t3a4ctk566y65eoad.onion/')
DEFAULT.apiURL.FLO_TEST.push('http://fdjrsde2qhfecvx6fkgmcidwkp34bdek7jo4y2fpqatrhzxtxkk6f4ad.onion/')
}
});
const util = floBlockchainAPI.util = {}; const util = floBlockchainAPI.util = {};
util.Sat_to_FLO = value => parseFloat((value / SATOSHI_IN_BTC).toFixed(8)); util.Sat_to_FLO = value => parseFloat((value / SATOSHI_IN_BTC).toFixed(8));
@ -61,9 +81,9 @@
var serverList = Array.from(allServerList); var serverList = Array.from(allServerList);
var curPos = floCrypto.randInt(0, serverList.length - 1); var curPos = floCrypto.randInt(0, serverList.length - 1);
function fetch_retry(apicall, rm_flosight) { function fetch_retry(apicall, rm_node) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let i = serverList.indexOf(rm_flosight) let i = serverList.indexOf(rm_node)
if (i != -1) serverList.splice(i, 1); if (i != -1) serverList.splice(i, 1);
curPos = floCrypto.randInt(0, serverList.length - 1); curPos = floCrypto.randInt(0, serverList.length - 1);
fetch_api(apicall, false) fetch_api(apicall, false)
@ -82,19 +102,19 @@
.then(result => resolve(result)) .then(result => resolve(result))
.catch(error => reject(error)); .catch(error => reject(error));
} else } else
reject("No floSight server working"); reject("No FLO blockbook server working");
} else { } else {
let flosight = serverList[curPos]; let serverURL = serverList[curPos];
fetch(flosight + apicall).then(response => { fetch(serverURL + apicall).then(response => {
if (response.ok) if (response.ok)
response.json().then(data => resolve(data)); response.json().then(data => resolve(data));
else { else {
fetch_retry(apicall, flosight) fetch_retry(apicall, serverURL)
.then(result => resolve(result)) .then(result => resolve(result))
.catch(error => reject(error)); .catch(error => reject(error));
} }
}).catch(error => { }).catch(error => {
fetch_retry(apicall, flosight) fetch_retry(apicall, serverURL)
.then(result => resolve(result)) .then(result => resolve(result))
.catch(error => reject(error)); .catch(error => reject(error));
}) })
@ -124,43 +144,27 @@
} }
//Get balance for the given Address //Get balance for the given Address
const getBalance = floBlockchainAPI.getBalance = function (addr, after = null) { const getBalance = floBlockchainAPI.getBalance = function (addr) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let api = `api/addr/${addr}/balance`, query_params = {}; let api = `api/address/${addr}`;
if (after) { promisedAPI(api, { details: "basic" })
if (typeof after === 'string' && /^[0-9a-z]{64}$/i.test(after)) .then(result => resolve(result["balance"]))
query_params.after = after; .catch(error => reject(error))
else return reject("Invalid 'after' parameter");
}
promisedAPI(api, query_params).then(result => {
if (typeof result === 'object' && result.lastItem) {
getBalance(addr, result.lastItem)
.then(r => resolve(util.toFixed(r + result.data)))
.catch(error => reject(error))
} else resolve(result);
}).catch(error => reject(error))
}); });
} }
const getUTXOs = address => new Promise((resolve, reject) => { function getScriptPubKey(address) {
promisedAPI(`api/addr/${address}/utxo`) var tx = bitjs.transaction();
.then(utxo => resolve(utxo)) tx.addoutput(address, 0);
.catch(error => reject(error)) let outputBuffer = tx.outputs.pop().script;
}) return Crypto.util.bytesToHex(outputBuffer)
}
const getUnconfirmedSpent = address => new Promise((resolve, reject) => { const getUTXOs = address => new Promise((resolve, reject) => {
readTxs(address, { mempool: "only" }).then(result => { promisedAPI(`api/utxo/${address}`, { confirmed: true }).then(utxos => {
let unconfirmedSpent = {}; let scriptPubKey = getScriptPubKey(address);
for (let tx of result.items) utxos.forEach(u => u.scriptPubKey = scriptPubKey);
if (tx.confirmations == 0) resolve(utxos);
for (let vin of tx.vin)
if (vin.addr === address) {
if (Array.isArray(unconfirmedSpent[vin.txid]))
unconfirmedSpent[vin.txid].push(vin.vout);
else
unconfirmedSpent[vin.txid] = [vin.vout];
}
resolve(unconfirmedSpent);
}).catch(error => reject(error)) }).catch(error => reject(error))
}) })
@ -180,32 +184,28 @@
var fee = DEFAULT.fee; var fee = DEFAULT.fee;
if (balance < sendAmt + fee) if (balance < sendAmt + fee)
return reject("Insufficient FLO balance!"); return reject("Insufficient FLO balance!");
getUnconfirmedSpent(senderAddr).then(unconfirmedSpent => { getUTXOs(senderAddr).then(utxos => {
getUTXOs(senderAddr).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; 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) { trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey);
if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout)) utxoAmt += utxos[i].amount;
continue; //A transaction has already used the utxo, but is unconfirmed. };
trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); }
utxoAmt += utxos[i].amount; if (utxoAmt < sendAmt + fee)
}; reject("Insufficient FLO: Some UTXOs are unconfirmed");
} else {
if (utxoAmt < sendAmt + fee) trx.addoutput(receiverAddr, sendAmt);
reject("Insufficient FLO: Some UTXOs are unconfirmed"); var change = utxoAmt - sendAmt - fee;
else { if (change > DEFAULT.minChangeAmt)
trx.addoutput(receiverAddr, sendAmt); trx.addoutput(senderAddr, change);
var change = utxoAmt - sendAmt - fee; trx.addflodata(floData.replace(/\n/g, ' '));
if (change > DEFAULT.minChangeAmt) resolve(trx);
trx.addoutput(senderAddr, change); }
trx.addflodata(floData.replace(/\n/g, ' '));
resolve(trx);
}
}).catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}) })
@ -293,34 +293,30 @@
if (balance < totalAmt + fee) if (balance < totalAmt + fee)
return reject("Insufficient FLO balance!"); return reject("Insufficient FLO balance!");
//get unconfirmed tx list //get unconfirmed tx list
getUnconfirmedSpent(floID).then(unconfirmedSpent => { getUTXOs(floID).then(utxos => {
getUTXOs(floID).then(utxos => { var trx = bitjs.transaction();
var trx = bitjs.transaction(); var utxoAmt = 0.0;
var utxoAmt = 0.0; for (let i = utxos.length - 1; (i >= 0) && (utxoAmt < totalAmt + fee); i--) {
for (let i = utxos.length - 1; (i >= 0) && (utxoAmt < totalAmt + 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) { trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey);
if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout)) utxoAmt += utxos[i].amount;
continue; //A transaction has already used the utxo, but is unconfirmed. };
trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); }
utxoAmt += utxos[i].amount; if (utxoAmt < totalAmt + fee)
}; reject("Insufficient FLO: Some UTXOs are unconfirmed");
} else {
if (utxoAmt < totalAmt + fee) for (let i = 0; i < count; i++)
reject("Insufficient FLO: Some UTXOs are unconfirmed"); trx.addoutput(floID, splitAmt);
else { var change = utxoAmt - totalAmt - fee;
for (let i = 0; i < count; i++) if (change > DEFAULT.minChangeAmt)
trx.addoutput(floID, splitAmt); trx.addoutput(floID, change);
var change = utxoAmt - totalAmt - fee; trx.addflodata(floData.replace(/\n/g, ' '));
if (change > DEFAULT.minChangeAmt) var signedTxHash = trx.sign(privKey, 1);
trx.addoutput(floID, change); broadcastTx(signedTxHash)
trx.addflodata(floData.replace(/\n/g, ' ')); .then(txid => resolve(txid))
var signedTxHash = trx.sign(privKey, 1); .catch(error => reject(error))
broadcastTx(signedTxHash) }
.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))
}) })
@ -551,33 +547,29 @@
var fee = DEFAULT.fee; var fee = DEFAULT.fee;
if (balance < sendAmt + fee) if (balance < sendAmt + fee)
return reject("Insufficient FLO balance!"); return reject("Insufficient FLO balance!");
getUnconfirmedSpent(senderAddr).then(unconfirmedSpent => { getUTXOs(senderAddr).then(utxos => {
getUTXOs(senderAddr).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; 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) { trx.addinput(utxos[i].txid, utxos[i].vout, redeemScript); //for multisig, script=redeemScript
if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout)) utxoAmt += utxos[i].amount;
continue; //A transaction has already used the utxo, but is unconfirmed. };
trx.addinput(utxos[i].txid, utxos[i].vout, redeemScript); //for multisig, script=redeemScript }
utxoAmt += utxos[i].amount; if (utxoAmt < sendAmt + fee)
}; reject("Insufficient FLO: Some UTXOs are unconfirmed");
} else {
if (utxoAmt < sendAmt + fee) for (let i in receivers)
reject("Insufficient FLO: Some UTXOs are unconfirmed"); trx.addoutput(receivers[i], amounts[i]);
else { var change = utxoAmt - sendAmt - fee;
for (let i in receivers) if (change > DEFAULT.minChangeAmt)
trx.addoutput(receivers[i], amounts[i]); trx.addoutput(senderAddr, change);
var change = utxoAmt - sendAmt - fee; trx.addflodata(floData.replace(/\n/g, ' '));
if (change > DEFAULT.minChangeAmt) resolve(trx);
trx.addoutput(senderAddr, change); }
trx.addflodata(floData.replace(/\n/g, ' '));
resolve(trx);
}
}).catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}); });
@ -773,20 +765,11 @@
const broadcastTx = floBlockchainAPI.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 Transaction Data");
var url = serverList[curPos] + 'api/tx/send';
fetch(url, { promisedAPI('/api/sendtx/' + signedTxHash)
method: "POST", .then(response => resolve(response["result"]))
headers: { .catch(error => reject(error))
'Content-Type': 'application/json'
},
body: `{"rawtx":"${signedTxHash}"}`
}).then(response => {
if (response.ok)
response.json().then(data => resolve(data.txid.result));
else
response.text().then(data => resolve(data));
}).catch(error => reject(error));
}) })
} }
@ -825,61 +808,96 @@
}) })
} }
//Read Txs of Address between from and to //Read Txs of Address
const readTxs = floBlockchainAPI.readTxs = function (addr, options = {}) { const readTxs = floBlockchainAPI.readTxs = function (addr, options = {}) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let api = `api/addrs/${addr}/txs`;
//API options //API options
let query_params = {}; let query_params = { details: 'txs' };
if (!isUndefined(options.after) || !isUndefined(options.before)) { //page options
if (!isUndefined(options.after)) if (!isUndefined(options.page) && Number.isInteger(options.page))
query_params.after = options.after; query_params.page = options.page;
if (!isUndefined(options.before)) if (!isUndefined(options.pageSize) && Number.isInteger(options.pageSize))
query_params.before = options.before; query_params.pageSize = options.pageSize;
} else { //only confirmed tx
if (!isUndefined(options.from)) if (options.confirmed) //Default is false in server, so only add confirmed filter if confirmed has a true value
query_params.from = options.from; query_params.confirmed = true;
if (!isUndefined(options.to))
query_params.to = options.to; promisedAPI(`api/address/${addr}`, query_params).then(response => {
} if (!Array.isArray(response.txs)) //set empty array if address doesnt have any tx
if (!isUndefined(options.latest)) response.txs = [];
query_params.latest = options.latest; resolve(response)
if (!isUndefined(options.mempool)) }).catch(error => reject(error))
query_params.mempool = options.mempool;
promisedAPI(api, query_params)
.then(response => resolve(response))
.catch(error => reject(error))
}); });
} }
//backward support (floBlockchainAPI < v2.5.6)
function readAllTxs_oldSupport(addr, options, ignoreOld = 0, cacheTotal = 0) {
return new Promise((resolve, reject) => {
readTxs(addr, options).then(response => {
cacheTotal += response.txs.length;
let n_remaining = response.txApperances - cacheTotal
if (n_remaining < ignoreOld) { // must remove tx that would have been fetch during prev call
let n_remove = ignoreOld - n_remaining;
resolve(response.txs.slice(0, -n_remove));
} else if (response.page == response.totalPages) //last page reached
resolve(response.txs);
else {
options.page = response.page + 1;
readAllTxs_oldSupport(addr, options, ignoreOld, cacheTotal)
.then(result => resolve(response.txs.concat(result)))
.catch(error => reject(error))
}
}).catch(error => reject(error))
})
}
function readAllTxs_new(addr, options, lastItem) {
return new Promise((resolve, reject) => {
readTxs(addr, options).then(response => {
let i = response.txs.findIndex(t => t.txid === lastItem);
if (i != -1) //found lastItem
resolve(response.txs.slice(0, i))
else if (response.page == response.totalPages) //last page reached
resolve(response.txs);
else {
options.page = response.page + 1;
readAllTxs_new(addr, options, lastItem)
.then(result => resolve(response.txs.concat(result)))
.catch(error => reject(error))
}
}).catch(error => reject(error))
})
}
//Read All Txs of Address (newest first) //Read All Txs of Address (newest first)
const readAllTxs = floBlockchainAPI.readAllTxs = function (addr, options = {}) { const readAllTxs = floBlockchainAPI.readAllTxs = function (addr, options = {}) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
readTxs(addr, options).then(response => { if (Number.isInteger(options.ignoreOld)) //backward support: data from floBlockchainAPI < v2.5.6
if (response.incomplete) { readAllTxs_oldSupport(addr, options, options.ignoreOld).then(txs => {
let next_options = Object.assign({}, options); let last_tx = txs.find(t => t.confirmations > 0);
if (options.latest) let new_lastItem = last_tx ? last_tx.txid : options.ignoreOld;
next_options.before = response.initItem; //update before for chain query (latest 1st)
else
next_options.after = response.lastItem; //update after for chain query (oldest 1st)
readAllTxs(addr, next_options).then(r => {
r.items = r.items.concat(response.items); //latest tx are 1st in array
resolve(r);
}).catch(error => reject(error))
} else
resolve({ resolve({
lastItem: response.lastItem || options.after, lastItem: new_lastItem,
items: response.items items: txs
}); })
})
}); }).catch(error => reject(error))
else //New format for floBlockchainAPI >= v2.5.6
readAllTxs_new(addr, options, options.after).then(txs => {
let last_tx = txs.find(t => t.confirmations > 0);
let new_lastItem = last_tx ? last_tx.txid : options.after;
resolve({
lastItem: new_lastItem,
items: txs
})
}).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
after : query after the given txid after : query after the given txid
before : query before the given txid confirmed : query only confirmed tx or not (options same as readAllTx, DEFAULT=true: only_confirmed_tx)
mempool : query mempool tx or not (options same as readAllTx, DEFAULT=false: ignore unconfirmed tx)
ignoreOld : ignore old txs (deprecated: support for backward compatibility only, cannot be used with 'after') ignoreOld : ignore old txs (deprecated: support for backward compatibility only, cannot be used with 'after')
sentOnly : filters only sent data sentOnly : filters only sent data
receivedOnly: filters only received data receivedOnly: filters only received data
@ -894,18 +912,14 @@
//fetch options //fetch options
let query_options = {}; let query_options = {};
query_options.mempool = isUndefined(options.mempool) ? false : options.mempool; //DEFAULT: ignore unconfirmed tx query_options.confirmed = isUndefined(options.confirmed) ? true : options.confirmed; //DEFAULT: ignore unconfirmed tx
if (!isUndefined(options.after) || !isUndefined(options.before)) {
if (!isUndefined(options.ignoreOld)) //Backward support
return reject("Invalid options: cannot use after/before and ignoreOld in same query");
//use passed after and/or before options (options remain undefined if not passed)
query_options.after = options.after;
query_options.before = options.before;
}
readAllTxs(addr, query_options).then(response => {
if (Number.isInteger(options.ignoreOld)) //backward support, cannot be used with options.after or options.before if (!isUndefined(options.after))
response.items.splice(-options.ignoreOld); //negative to count from end of the array query_options.after = options.after;
else if (!isUndefined(options.ignoreOld))
query_options.ignoreOld = options.ignoreOld;
readAllTxs(addr, query_options).then(response => {
if (typeof options.senders === "string") options.senders = [options.senders]; if (typeof options.senders === "string") options.senders = [options.senders];
if (typeof options.receivers === "string") options.receivers = [options.receivers]; if (typeof options.receivers === "string") options.receivers = [options.receivers];
@ -916,9 +930,9 @@
if (!tx.confirmations) //unconfirmed transactions: this should not happen as we send mempool=false in API query if (!tx.confirmations) //unconfirmed transactions: this should not happen as we send mempool=false in API query
return false; return false;
if (options.sentOnly && !tx.vin.some(vin => vin.addr === addr)) if (options.sentOnly && !tx.vin.some(vin => vin.addresses[0] === addr))
return false; return false;
else if (Array.isArray(options.senders) && !tx.vin.some(vin => options.senders.includes(vin.addr))) else if (Array.isArray(options.senders) && !tx.vin.some(vin => options.senders.includes(vin.addresses[0])))
return false; return false;
if (options.receivedOnly && !tx.vout.some(vout => vout.scriptPubKey.addresses[0] === addr)) if (options.receivedOnly && !tx.vout.some(vout => vout.scriptPubKey.addresses[0] === addr))
@ -944,7 +958,7 @@
txid: tx.txid, txid: tx.txid,
time: tx.time, time: tx.time,
blockheight: tx.blockheight, blockheight: tx.blockheight,
senders: new Set(tx.vin.map(v => v.addr)), senders: new Set(tx.vin.map(v => v.addresses[0])),
receivers: new Set(tx.vout.map(v => v.scriptPubKey.addresses[0])), receivers: new Set(tx.vout.map(v => v.scriptPubKey.addresses[0])),
data: tx.floData data: tx.floData
} : tx.floData); } : tx.floData);
@ -964,8 +978,7 @@
caseFn: (function) flodata => return bool value caseFn: (function) flodata => return bool value
options can be used to filter data options can be used to filter data
after : query after the given txid after : query after the given txid
before : query before the given txid confirmed : query only confirmed tx or not (options same as readAllTx, DEFAULT=true: only_confirmed_tx)
mempool : query mempool tx or not (options same as readAllTx, DEFAULT=false: ignore unconfirmed tx)
sentOnly : filters only sent data sentOnly : filters only sent data
receivedOnly: filters only received data receivedOnly: filters only received data
tx : (boolean) resolve tx data or not (resolves an Array of Object with tx details) tx : (boolean) resolve tx data or not (resolves an Array of Object with tx details)
@ -975,23 +988,37 @@
const getLatestData = floBlockchainAPI.getLatestData = function (addr, caseFn, options = {}) { const getLatestData = floBlockchainAPI.getLatestData = function (addr, caseFn, options = {}) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
//fetch options //fetch options
let query_options = { latest: true }; let query_options = {};
query_options.mempool = isUndefined(options.mempool) ? false : options.mempool; //DEFAULT: ignore unconfirmed tx query_options.confirmed = isUndefined(options.confirmed) ? true : options.confirmed; //DEFAULT: confirmed tx only
if (!isUndefined(options.after)) query_options.after = options.after; if (!isUndefined(options.page))
if (!isUndefined(options.before)) query_options.before = options.before; query_options.page = options.page;
//if (!isUndefined(options.after)) query_options.after = options.after;
let new_lastItem;
readTxs(addr, query_options).then(response => { readTxs(addr, query_options).then(response => {
//lastItem confirmed tx checked
if (!new_lastItem) {
let last_tx = response.items.find(t => t.confirmations > 0);
if (last_tx)
new_lastItem = last_tx.txid;
}
if (typeof options.senders === "string") options.senders = [options.senders]; if (typeof options.senders === "string") options.senders = [options.senders];
if (typeof options.receivers === "string") options.receivers = [options.receivers]; if (typeof options.receivers === "string") options.receivers = [options.receivers];
//check if `after` txid is in the response
let i_after = response.txs.findIndex(t => t.txid === options.after);
if (i_after != -1) //found lastItem, hence remove it and all txs before that
response.items.splice(i_after);
var item = response.items.find(tx => { var item = response.items.find(tx => {
if (!tx.confirmations) //unconfirmed transactions: this should not happen as we send mempool=false in API query if (!tx.confirmations) //unconfirmed transactions: this should not happen as we send mempool=false in API query
return false; return false;
if (options.sentOnly && !tx.vin.some(vin => vin.addr === addr)) if (options.sentOnly && !tx.vin.some(vin => vin.addresses[0] === addr))
return false; return false;
else if (Array.isArray(options.senders) && !tx.vin.some(vin => options.senders.includes(vin.addr))) else if (Array.isArray(options.senders) && !tx.vin.some(vin => options.senders.includes(vin.addresses[0])))
return false; return false;
if (options.receivedOnly && !tx.vout.some(vout => vout.scriptPubKey.addresses[0] === addr)) if (options.receivedOnly && !tx.vout.some(vout => vout.scriptPubKey.addresses[0] === addr))
@ -1004,35 +1031,34 @@
//if item found, then resolve the result //if item found, then resolve the result
if (!isUndefined(item)) { if (!isUndefined(item)) {
const result = { lastItem: response.lastItem }; const result = { lastItem: new_lastItem || item.txid };
if (options.tx) { if (options.tx) {
result.item = { result.item = {
txid: tx.txid, txid: item.txid,
time: tx.time, time: item.time,
blockheight: tx.blockheight, blockheight: item.blockheight,
senders: new Set(tx.vin.map(v => v.addr)), senders: new Set(item.vin.map(v => v.addresses[0])),
receivers: new Set(tx.vout.map(v => v.scriptPubKey.addresses[0])), receivers: new Set(item.vout.map(v => v.scriptPubKey.addresses[0])),
data: tx.floData data: item.floData
} }
} else } else
result.data = tx.floData; result.data = item.floData;
return resolve(result); return resolve(result);
} }
if (response.page == response.totalPages || i_after != -1) //reached last page to check
resolve({ lastItem: new_lastItem || options.after }); //no data match the caseFn, resolve just the lastItem
//else if address needs chain query //else if address needs chain query
else if (response.incomplete) { else {
let next_options = Object.assign({}, options); options.page = response.page + 1;
options.before = response.initItem; //this fn uses latest option, so using before to chain query getLatestData(addr, caseFn, options)
getLatestData(addr, caseFn, next_options).then(r => { .then(result => resolve(result))
r.lastItem = response.lastItem; //update last key as it should be the newest tx .catch(error => reject(error))
resolve(r);
}).catch(error => reject(error))
} }
//no data match the caseFn, resolve just the lastItem
else
resolve({ lastItem: response.lastItem });
}).catch(error => reject(error)) }).catch(error => reject(error))
}) })
} }
})('object' === typeof module ? module.exports : window.floBlockchainAPI = {}); })('object' === typeof module ? module.exports : window.floBlockchainAPI = {});

1
floBlockchainAPI.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -1,4 +1,4 @@
(function (EXPORTS) { //floCloudAPI v2.4.3a (function (EXPORTS) { //floCloudAPI v2.4.5a
/* FLO Cloud operations to send/request application data*/ /* FLO Cloud operations to send/request application data*/
'use strict'; 'use strict';
const floCloudAPI = EXPORTS; const floCloudAPI = EXPORTS;
@ -195,14 +195,24 @@
floCloudAPI.init = function startCloudProcess(nodes) { floCloudAPI.init = function startCloudProcess(nodes) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
try { try {
// accept only plain-ish objects
nodes = (nodes && typeof nodes === 'object' && !Array.isArray(nodes)) ? nodes : {};
supernodes = nodes; supernodes = nodes;
// reset liveness bookkeeping for the new set
if (_inactive && typeof _inactive.clear === 'function') _inactive.clear();
// (re)build the bucket with current IDs
kBucket = new K_Bucket(DEFAULT.SNStorageID, Object.keys(supernodes)); kBucket = new K_Bucket(DEFAULT.SNStorageID, Object.keys(supernodes));
resolve('Cloud init successful'); resolve('Cloud init successful');
} catch (error) { } catch (error) {
reject(error); reject(error);
} }
}) });
} };
Object.defineProperty(floCloudAPI, 'kBucket', { Object.defineProperty(floCloudAPI, 'kBucket', {
get: () => kBucket get: () => kBucket
@ -227,24 +237,27 @@
function ws_activeConnect(snID, reverse = false) { function ws_activeConnect(snID, reverse = false) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (_inactive.size === kBucket.list.length) // Safe guard: uninitialized kBucket, empty list, or all inactive
if (!kBucket || !kBucket.list || !kBucket.list.length || _inactive.size === kBucket.list.length)
return reject('Cloud offline'); return reject('Cloud offline');
if (!(snID in supernodes))
snID = kBucket.closestNode(proxyID(snID)); if (!(snID in supernodes)) {
var closest = kBucket.closestNode(proxyID(snID));
if (!closest) return reject('Cloud offline'); // no candidate to try
snID = closest;
}
ws_connect(snID) ws_connect(snID)
.then(node => resolve(node)) .then(node => resolve(node))
.catch(error => { .catch(error => {
if (reverse) var nxtNode = reverse ? kBucket.prevNode(snID) : kBucket.nextNode(snID);
var nxtNode = kBucket.prevNode(snID); if (!nxtNode || nxtNode === snID) return reject('Cloud offline'); // nothing else to try
else ws_activeConnect(nxtNode, reverse).then(resolve).catch(reject);
var nxtNode = kBucket.nextNode(snID); });
ws_activeConnect(nxtNode, reverse) });
.then(node => resolve(node))
.catch(error => reject(error))
})
})
} }
function fetch_API(snID, data) { function fetch_API(snID, data) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (_inactive.has(snID)) if (_inactive.has(snID))
@ -265,25 +278,28 @@
function fetch_ActiveAPI(snID, data, reverse = false) { function fetch_ActiveAPI(snID, data, reverse = false) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (_inactive.size === kBucket.list.length) // Safe guard: uninitialized kBucket, empty list, or all inactive
if (!kBucket || !kBucket.list || !kBucket.list.length || _inactive.size === kBucket.list.length)
return reject('Cloud offline'); return reject('Cloud offline');
if (!(snID in supernodes))
snID = kBucket.closestNode(proxyID(snID)); if (!(snID in supernodes)) {
var closest = kBucket.closestNode(proxyID(snID));
if (!closest) return reject('Cloud offline'); // no candidate available
snID = closest;
}
fetch_API(snID, data) fetch_API(snID, data)
.then(result => resolve(result)) .then(resolve)
.catch(error => { .catch(error => {
_inactive.add(snID) _inactive.add(snID);
if (reverse) var nxtNode = reverse ? kBucket.prevNode(snID) : kBucket.nextNode(snID);
var nxtNode = kBucket.prevNode(snID); if (!nxtNode || nxtNode === snID) return reject('Cloud offline'); // nothing else to try
else fetch_ActiveAPI(nxtNode, data, reverse).then(resolve).catch(reject);
var nxtNode = kBucket.nextNode(snID); });
fetch_ActiveAPI(nxtNode, data, reverse) });
.then(result => resolve(result))
.catch(error => reject(error));
})
})
} }
function singleRequest(floID, data_obj, method = "POST") { function singleRequest(floID, data_obj, method = "POST") {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let data; let data;
@ -374,13 +390,31 @@
const util = floCloudAPI.util = {}; const util = floCloudAPI.util = {};
//Updating encoding/Decoding to modern standards
const encodeMessage = util.encodeMessage = function (message) { const encodeMessage = util.encodeMessage = function (message) {
return btoa(unescape(encodeURIComponent(JSON.stringify(message)))) const bytes = new TextEncoder().encode(JSON.stringify(message));
} let bin = "";
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
return btoa(bin);
};
const decodeMessage = util.decodeMessage = function (message) { const decodeMessage = util.decodeMessage = function (message) {
return JSON.parse(decodeURIComponent(escape(atob(message)))) try {
} // try modern decode first
const bin = atob(message);
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
return JSON.parse(new TextDecoder().decode(bytes));
} catch (e1) {
try {
// fallback to legacy decode
return JSON.parse(decodeURIComponent(escape(atob(message))));
} catch (e2) {
// final fallback: return raw string to avoid hard crash
return message;
}
}
};
const filterKey = util.filterKey = function (type, options = {}) { const filterKey = util.filterKey = function (type, options = {}) {
return type + (options.comment ? ':' + options.comment : '') + return type + (options.comment ? ':' + options.comment : '') +
@ -468,21 +502,59 @@
function storeGeneral(fk, dataSet) { function storeGeneral(fk, dataSet) {
try { try {
console.log(dataSet) if (!dataSet || typeof dataSet !== "object") return;
if (typeof generalData[fk] !== "object")
generalData[fk] = {} // Ensure containers exist
for (let vc in dataSet) { if (typeof generalData[fk] !== "object" || generalData[fk] === null)
generalData[fk][vc] = dataSet[vc]; generalData[fk] = {};
if (dataSet[vc].log_time > lastVC[fk]) if (typeof lastVC[fk] !== "number")
lastVC[fk] = dataSet[vc].log_time; lastVC[fk] = 0;
// Merge data and track latest log_time
let updated = false;
let newLast = lastVC[fk];
for (const vc in dataSet) {
const rec = dataSet[vc];
// Skip bad records
if (!rec || typeof rec !== "object") continue;
// Assign only if changed reference (cheap check)
if (generalData[fk][vc] !== rec) {
generalData[fk][vc] = rec;
updated = true;
}
if (typeof rec.log_time === "number" && rec.log_time > newLast) {
newLast = rec.log_time;
updated = true;
}
} }
compactIDB.writeData("lastVC", lastVC[fk], fk)
compactIDB.writeData("generalData", generalData[fk], fk) if (!updated) return; // nothing new, avoid IDB writes
lastVC[fk] = newLast;
// --- Debounce writes per fk to avoid IDB thrash ---
storeGeneral._pending = storeGeneral._pending || Object.create(null);
const pend = storeGeneral._pending;
clearTimeout(pend[fk]);
pend[fk] = setTimeout(() => {
try {
// Fire-and-forget; callers dont wait on these
compactIDB.writeData("lastVC", lastVC[fk], fk);
compactIDB.writeData("generalData", generalData[fk], fk);
} catch (e) {
console.error(e);
}
}, 50);
} catch (error) { } catch (error) {
console.error(error) console.error(error);
} }
} }
function objectifier(data) { function objectifier(data) {
if (!Array.isArray(data)) if (!Array.isArray(data))
data = [data]; data = [data];
@ -551,7 +623,7 @@
} }
//request any data from supernode cloud //request any data from supernode cloud
const requestApplicationData = floCloudAPI.requestApplicationData = function (type, options = {}) { const _requestApplicationData = function (type, options = {}) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var request = { var request = {
receiverID: options.receiverID || DEFAULT.adminID, receiverID: options.receiverID || DEFAULT.adminID,
@ -582,6 +654,17 @@
}) })
} }
floCloudAPI.requestApplicationData = function (type, options = {}) {
return new Promise((resolve, reject) => {
let single_request_mode = !(options.callback instanceof Function);
_requestApplicationData(type, options).then(data => {
if (single_request_mode)
resolve(objectifier(data))
else resolve(data);
}).catch(error => reject(error))
})
}
/*(NEEDS UPDATE) /*(NEEDS UPDATE)
//delete data from supernode cloud (received only) //delete data from supernode cloud (received only)
floCloudAPI.deleteApplicationData = function(vectorClocks, options = {}) { floCloudAPI.deleteApplicationData = function(vectorClocks, options = {}) {
@ -609,49 +692,39 @@
}) })
} }
*/ */
/*(NEEDS UPDATE) //edit comment of data in supernode cloud (sender only)
//edit comment of data in supernode cloud (mutable comments only) floCloudAPI.editApplicationData = function (vectorClock, comment_edit, options = {}) {
floCloudAPI.editApplicationData = function(vectorClock, newComment, oldData, options = {}) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let p0 //request the data from cloud for resigning
if (!oldData) { let req_options = Object.assign({}, options);
options.atVectorClock = vectorClock; req_options.atVectorClock = vectorClock;
options.callback = false; _requestApplicationData(undefined, req_options).then(result => {
p0 = requestApplicationData(false, options) if (!result.length)
} else return reject("Data not found");
p0 = Promise.resolve({ let data = result[0];
vectorClock: { if (data.senderID !== user.id)
...oldData return reject("Only sender can edit comment");
} data.comment = comment_edit;
}) let hashcontent = ["receiverID", "time", "application", "type", "message", "comment"]
p0.then(d => { .map(d => data[d]).join("|");
if (d.senderID != user.id) let re_sign = user.sign(hashcontent);
return reject("Invalid requestorID") var request = {
else if (!d.comment.startsWith("EDIT:")) receiverID: options.receiverID || DEFAULT.adminID,
return reject("Data immutable")
let data = {
requestorID: user.id, requestorID: user.id,
receiverID: d.receiverID, pubKey: user.public,
time: Date.now(), time: Date.now(),
application: d.application, vectorClock: vectorClock,
edit: { edit: comment_edit,
vectorClock: vectorClock, re_sign: re_sign
comment: newComment
}
} }
d.comment = data.edit.comment; let request_hash = ["time", "vectorClock", "edit", "re_sign"].map(d => request[d]).join("|");
let hashcontent = ["receiverID", "time", "application", "type", "message", request.sign = user.sign(request_hash);
"comment" singleRequest(request.receiverID, request)
] .then(result => resolve(result))
.map(x => d[x]).join("|")
data.edit.sign = user.sign(hashcontent)
singleRequest(data.receiverID, data)
.then(result => resolve("Data comment updated"))
.catch(error => reject(error)) .catch(error => reject(error))
}) }).catch(error => reject(error))
}) })
} }
*/
//tag data in supernode cloud (subAdmin access only) //tag data in supernode cloud (subAdmin access only)
floCloudAPI.tagApplicationData = function (vectorClock, tag, options = {}) { floCloudAPI.tagApplicationData = function (vectorClock, tag, options = {}) {
@ -719,11 +792,11 @@
storeGeneral(fk, d); storeGeneral(fk, d);
options.callback(d, e) options.callback(d, e)
} }
requestApplicationData(type, new_options) _requestApplicationData(type, new_options)
.then(result => resolve(result)) .then(result => resolve(result))
.catch(error => reject(error)) .catch(error => reject(error))
} else { } else {
requestApplicationData(type, options).then(dataSet => { _requestApplicationData(type, options).then(dataSet => {
storeGeneral(fk, objectifier(dataSet)) storeGeneral(fk, objectifier(dataSet))
resolve(dataSet) resolve(dataSet)
}).catch(error => reject(error)) }).catch(error => reject(error))
@ -748,7 +821,7 @@
} }
delete options.callback; delete options.callback;
} }
requestApplicationData(objectName, options).then(dataSet => { _requestApplicationData(objectName, options).then(dataSet => {
updateObject(objectName, objectifier(dataSet)); updateObject(objectName, objectifier(dataSet));
delete options.comment; delete options.comment;
options.lowerVectorClock = lastVC[objectName] + 1; options.lowerVectorClock = lastVC[objectName] + 1;
@ -756,11 +829,11 @@
if (callback) { if (callback) {
let new_options = Object.create(options); let new_options = Object.create(options);
new_options.callback = callback; new_options.callback = callback;
requestApplicationData(objectName, new_options) _requestApplicationData(objectName, new_options)
.then(result => resolve(result)) .then(result => resolve(result))
.catch(error => reject(error)) .catch(error => reject(error))
} else { } else {
requestApplicationData(objectName, options).then(dataSet => { _requestApplicationData(objectName, options).then(dataSet => {
updateObject(objectName, objectifier(dataSet)) updateObject(objectName, objectifier(dataSet))
resolve(appObjects[objectName]) resolve(appObjects[objectName])
}).catch(error => reject(error)) }).catch(error => reject(error))
@ -811,6 +884,67 @@
}) })
} }
//upload file
floCloudAPI.uploadFile = function (fileBlob, type, options = {}) {
return new Promise((resolve, reject) => {
if (!(fileBlob instanceof File) && !(fileBlob instanceof Blob))
return reject("file must be instance of File/Blob");
fileBlob.arrayBuffer().then(arraybuf => {
let file_data = { type: fileBlob.type, name: fileBlob.name };
file_data.content = Crypto.util.bytesToBase64(new Uint8Array(arraybuf));
if (options.encrypt) {
let encryptionKey = options.encrypt === true ?
floGlobals.settings.encryptionKey : options.encrypt
file_data = floCrypto.encryptData(JSON.stringify(file_data), encryptionKey)
}
sendApplicationData(file_data, type, options)
.then(({ vectorClock, receiverID, type, application }) => resolve({ vectorClock, receiverID, type, application }))
.catch(error => reject(error))
}).catch(error => reject(error))
})
}
//download file
floCloudAPI.downloadFile = function (vectorClock, options = {}) {
return new Promise((resolve, reject) => {
options.atVectorClock = vectorClock;
_requestApplicationData(options.type, options).then(result => {
if (!result.length)
return reject("File not found");
result = result[0];
try {
let file_data = decodeMessage(result.message);
//file is encrypted: decryption required
if (file_data instanceof Object && "secret" in file_data) {
if (!options.decrypt)
return reject("Data is encrypted");
let decryptionKey = (options.decrypt === true) ? Crypto.AES.decrypt(user_private, aes_key) : options.decrypt;
if (!Array.isArray(decryptionKey))
decryptionKey = [decryptionKey];
let flag = false;
for (let key of decryptionKey) {
try {
let tmp = floCrypto.decryptData(file_data, key);
file_data = JSON.parse(tmp);
flag = true;
break;
} catch (error) { }
}
if (!flag)
return reject("Unable to decrypt file: Invalid private key");
}
//reconstruct the file
let arraybuf = new Uint8Array(Crypto.util.base64ToBytes(file_data.content))
result.file = new File([arraybuf], file_data.name, { type: file_data.type });
resolve(result)
} catch (error) {
console.error(error);
reject("Data is not a file");
}
}).catch(error => reject(error))
})
}
/* /*
Functions: Functions:
findDiff(original, updatedObj) returns an object with the added, deleted and updated differences findDiff(original, updatedObj) returns an object with the added, deleted and updated differences
@ -1052,4 +1186,4 @@
})(); })();
})('object' === typeof module ? module.exports : window.floCloudAPI = {}); })('object' === typeof module ? module.exports : window.floCloudAPI = {});

1
floCloudAPI.min.js vendored Normal file

File diff suppressed because one or more lines are too long

1
floCrypto.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -1,4 +1,4 @@
(function (EXPORTS) { //floDapps v2.4.0 (function (EXPORTS) { //floDapps v2.4.1
/* General functions for FLO Dapps*/ /* General functions for FLO Dapps*/
'use strict'; 'use strict';
const floDapps = EXPORTS; const floDapps = EXPORTS;
@ -144,7 +144,7 @@
} }
}); });
var subAdmins, trustedIDs, settings; var subAdmins = [], trustedIDs = [], settings = {};
Object.defineProperties(floGlobals, { Object.defineProperties(floGlobals, {
subAdmins: { subAdmins: {
get: () => subAdmins get: () => subAdmins
@ -172,12 +172,7 @@
//general //general
lastTx: {}, lastTx: {},
//supernode (cloud list) //supernode (cloud list)
supernodes: { supernodes: {}
indexes: {
uri: null,
pubKey: null
}
}
} }
var obs_a = { var obs_a = {
//login credentials //login credentials
@ -254,103 +249,154 @@
const startUpFunctions = []; const startUpFunctions = [];
startUpFunctions.push(function readSupernodeListFromAPI() { startUpFunctions.push(function readSupernodeListFromAPI() {
return new Promise((resolve, reject) => { return new Promise((resolve) => {
if (!startUpOptions.cloud) if (!startUpOptions.cloud)
return resolve("No cloud for this app"); return resolve("No cloud for this app");
compactIDB.readData("lastTx", floCloudAPI.SNStorageID, DEFAULT.root).then(lastTx => {
var query_options = { sentOnly: true, pattern: floCloudAPI.SNStorageName }; const CLOUD_KEY = "floCloudAPI#" + floCloudAPI.SNStorageID;
if (typeof lastTx == 'number') //lastTx is tx count (*backward support)
query_options.ignoreOld = lastTx; // Fallback: init from cached nodes (never reject)
else if (typeof lastTx == 'string') //lastTx is txid of last tx const initFromCache = (tag) =>
query_options.after = lastTx; compactIDB.readData("supernodes", CLOUD_KEY, DEFAULT.root)
//fetch data from flosight .then(nodes => {
floBlockchainAPI.readData(floCloudAPI.SNStorageID, query_options).then(result => { nodes = nodes || {};
for (var i = result.data.length - 1; i >= 0; i--) { return floCloudAPI.init(nodes)
var content = JSON.parse(result.data[i])[floCloudAPI.SNStorageName]; .then(r => resolve(`${tag} (from cache)\n${r}`))
for (let sn in content.removeNodes) .catch(() => resolve(`${tag} (cache present, init skipped)`));
compactIDB.removeData("supernodes", sn, DEFAULT.root);
for (let sn in content.newNodes)
compactIDB.writeData("supernodes", content.newNodes[sn], sn, DEFAULT.root);
for (let sn in content.updateNodes)
compactIDB.readData("supernodes", sn, DEFAULT.root).then(r => {
r = r || {}
r.uri = content.updateNodes[sn];
compactIDB.writeData("supernodes", r, sn, DEFAULT.root);
});
}
compactIDB.writeData("lastTx", result.lastItem, floCloudAPI.SNStorageID, DEFAULT.root);
compactIDB.readAllData("supernodes", DEFAULT.root).then(nodes => {
floCloudAPI.init(nodes)
.then(result => resolve("Loaded Supernode list\n" + result))
.catch(error => reject(error))
}) })
}) .catch(() => resolve(`${tag} (no cache)`));
}).catch(error => reject(error))
}) compactIDB.readData("lastTx", CLOUD_KEY, DEFAULT.root).then(lastTx => {
const query_options = { sentOnly: true, pattern: floCloudAPI.SNStorageName };
if (typeof lastTx === 'number') // backward support (tx count)
query_options.ignoreOld = lastTx;
else if (typeof lastTx === 'string') // last txid
query_options.after = lastTx;
// Try online; if it fails, fall back to cache
floBlockchainAPI.readData(floCloudAPI.SNStorageID, query_options).then(result => {
compactIDB.readData("supernodes", CLOUD_KEY, DEFAULT.root).then(nodes => {
nodes = nodes || {};
for (let i = result.data.length - 1; i >= 0; i--) {
const content = JSON.parse(result.data[i])[floCloudAPI.SNStorageName];
if (!content || typeof content !== 'object') continue;
if (content.removeNodes)
for (let sn in content.removeNodes) delete nodes[sn];
if (content.newNodes)
for (let sn in content.newNodes) nodes[sn] = content.newNodes[sn];
if (content.updateNodes)
for (let sn in content.updateNodes)
if (sn in nodes) nodes[sn].uri = content.updateNodes[sn];
}
Promise.all([
compactIDB.writeData("lastTx", result.lastItem, CLOUD_KEY, DEFAULT.root),
compactIDB.writeData("supernodes", nodes, CLOUD_KEY, DEFAULT.root)
]).then(() => {
floCloudAPI.init(nodes)
.then(r => resolve("Loaded Supernode list\n" + r))
.catch(() => resolve("Loaded Supernode list (init deferred)"));
}).catch(() => resolve("Supernode list updated (persist partial)"));
}).catch(() => initFromCache("Supernode list read failed"));
}).catch(() => initFromCache("Supernode network fetch failed"));
}).catch(() => initFromCache("Supernode lastTx read failed"));
});
}); });
startUpFunctions.push(function readAppConfigFromAPI() { startUpFunctions.push(function readAppConfigFromAPI() {
return new Promise((resolve, reject) => { return new Promise((resolve) => {
if (!startUpOptions.app_config) if (!startUpOptions.app_config)
return resolve("No configs for this app"); return resolve("No configs for this app");
compactIDB.readData("lastTx", `${DEFAULT.application}|${DEFAULT.adminID}`, DEFAULT.root).then(lastTx => {
var query_options = { sentOnly: true, pattern: DEFAULT.application }; // small helper: load cached directives into memory and resolve
if (typeof lastTx == 'number') //lastTx is tx count (*backward support) const loadFromIDB = (msg) => Promise.all([
query_options.ignoreOld = lastTx; compactIDB.readAllData("subAdmins"),
else if (typeof lastTx == 'string') //lastTx is txid of last tx compactIDB.readAllData("trustedIDs"),
query_options.after = lastTx; compactIDB.readAllData("settings")
//fetch data from flosight ]).then(([sub, trust, set]) => {
subAdmins = Object.keys(sub || {}); // arrays of IDs
trustedIDs = Object.keys(trust || {});
settings = set || {};
resolve(msg);
}).catch(() => {
// safe defaults if cache missing
subAdmins = []; trustedIDs = []; settings = {};
resolve(msg + " (no local cache)");
});
// If cloud is disabled, use cached config and move on
if (!startUpOptions.cloud)
return loadFromIDB("Read app configuration from local cache (offline)");
const lastKey = `${DEFAULT.application}|${DEFAULT.adminID}`;
// Try to read lastTx; on failure, just use cache (dont block startup)
compactIDB.readData("lastTx", lastKey, DEFAULT.root).then(lastTx => {
const query_options = { sentOnly: true, pattern: DEFAULT.application };
if (typeof lastTx === 'number') query_options.ignoreOld = lastTx;
else if (typeof lastTx === 'string') query_options.after = lastTx;
// Fetch deltas from chain; on failure, fall back to cache
floBlockchainAPI.readData(DEFAULT.adminID, query_options).then(result => { floBlockchainAPI.readData(DEFAULT.adminID, query_options).then(result => {
for (var i = result.data.length - 1; i >= 0; i--) { for (let i = result.data.length - 1; i >= 0; i--) {
var content = JSON.parse(result.data[i])[DEFAULT.application]; const content = JSON.parse(result.data[i])[DEFAULT.application];
if (!content || typeof content !== "object") if (!content || typeof content !== "object") continue;
continue;
if (Array.isArray(content.removeSubAdmin)) if (Array.isArray(content.removeSubAdmin))
for (var j = 0; j < content.removeSubAdmin.length; j++) for (let j = 0; j < content.removeSubAdmin.length; j++)
compactIDB.removeData("subAdmins", content.removeSubAdmin[j]); compactIDB.removeData("subAdmins", content.removeSubAdmin[j]);
if (Array.isArray(content.addSubAdmin)) if (Array.isArray(content.addSubAdmin))
for (var k = 0; k < content.addSubAdmin.length; k++) for (let k = 0; k < content.addSubAdmin.length; k++)
compactIDB.writeData("subAdmins", true, content.addSubAdmin[k]); compactIDB.writeData("subAdmins", true, content.addSubAdmin[k]);
if (Array.isArray(content.removeTrustedID)) if (Array.isArray(content.removeTrustedID))
for (var j = 0; j < content.removeTrustedID.length; j++) for (let j = 0; j < content.removeTrustedID.length; j++)
compactIDB.removeData("trustedIDs", content.removeTrustedID[j]); compactIDB.removeData("trustedIDs", content.removeTrustedID[j]);
if (Array.isArray(content.addTrustedID)) if (Array.isArray(content.addTrustedID))
for (var k = 0; k < content.addTrustedID.length; k++) for (let k = 0; k < content.addTrustedID.length; k++)
compactIDB.writeData("trustedIDs", true, content.addTrustedID[k]); compactIDB.writeData("trustedIDs", true, content.addTrustedID[k]);
if (content.settings) if (content.settings)
for (let l in content.settings) for (let l in content.settings)
compactIDB.writeData("settings", content.settings[l], l) compactIDB.writeData("settings", content.settings[l], l);
} }
compactIDB.writeData("lastTx", result.lastItem, `${DEFAULT.application}|${DEFAULT.adminID}`, DEFAULT.root);
compactIDB.readAllData("subAdmins").then(result => { // persist last item marker (best effort)
subAdmins = Object.keys(result); compactIDB.writeData("lastTx", result.lastItem, lastKey, DEFAULT.root).catch(() => {});
compactIDB.readAllData("trustedIDs").then(result => {
trustedIDs = Object.keys(result); // load fresh values from IDB into memory and finish
compactIDB.readAllData("settings").then(result => { loadFromIDB("Read app configuration from blockchain");
settings = result; }).catch(() => {
resolve("Read app configuration from blockchain"); // network failed → boot from cache
}) loadFromIDB("Read app configuration from local cache (network fail)");
}) });
}) }).catch(() => {
}) // couldn't read lastTx → still boot from cache
}).catch(error => reject(error)) loadFromIDB("Read app configuration from local cache (no lastTx)");
}) });
});
}); });
startUpFunctions.push(function loadDataFromAppIDB() { startUpFunctions.push(function loadDataFromAppIDB() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!startUpOptions.cloud) const loadData = ["appObjects", "generalData", "lastVC"];
return resolve("No cloud for this app");
var loadData = ["appObjects", "generalData", "lastVC"] // If cloud is disabled AND no IDB stores are expected, skip early
var promises = [] if (!startUpOptions.cloud && (!initIndexedDB.appObs || Object.keys(initIndexedDB.appObs).length === 0))
for (var i = 0; i < loadData.length; i++) return resolve("No cloud and no local data to load");
promises[i] = compactIDB.readAllData(loadData[i])
Promise.all(promises).then(results => { // Otherwise, read from IDB
for (var i = 0; i < loadData.length; i++) Promise.all(loadData.map(item => compactIDB.readAllData(item)))
floGlobals[loadData[i]] = results[i] .then(results => {
resolve("Loaded Data from app IDB") for (let i = 0; i < loadData.length; i++)
}).catch(error => reject(error)) floGlobals[loadData[i]] = results[i];
}) resolve("Loaded Data from app IDB");
})
.catch(error => reject(error));
});
}); });
var keyInput = type => new Promise((resolve, reject) => { var keyInput = type => new Promise((resolve, reject) => {
@ -842,4 +888,4 @@
.catch(error => reject(error)) .catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}); });
})('object' === typeof module ? module.exports : window.floDapps = {}); })('object' === typeof module ? module.exports : window.floDapps = {});

1
floDapps.min.js vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

1
floTokenAPI.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -26,14 +26,14 @@
})(); })();
</script> </script>
<script src="lib.js"></script> <script src="lib.js" type="text/javascript"></script>
<script src="floCrypto.js"></script> <script src="floCrypto.js" type="text/javascript"></script>
<script src="btcOperator.js"></script> <script src="btcOperator.js" type="text/javascript"></script>
<script src="floBlockchainAPI.js"></script> <script src="floBlockchainAPI.js" type="text/javascript"></script>
<script src="floTokenAPI.js"></script> <script src="floTokenAPI.js" type="text/javascript"></script>
<script src="compactIDB.js"></script> <script src="compactIDB.js" type="text/javascript"></script>
<script src="floCloudAPI.js"></script> <script src="floCloudAPI.js" type="text/javascript"></script>
<script src="floDapps.js"></script> <script src="floDapps.js" type="text/javascript"></script>
<script id="onLoadStartUp"> <script id="onLoadStartUp">
function onLoadStartUp() { function onLoadStartUp() {
if (window.quick) return; if (window.quick) return;

57
lib.min.js vendored Normal file

File diff suppressed because one or more lines are too long