Compare commits

...

10 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
8 changed files with 308 additions and 159 deletions

View File

@ -1,4 +1,4 @@
(function (EXPORTS) { //btcOperator v1.2.8
(function (EXPORTS) { //btcOperator v1.2.10
/* BTC Crypto and API Operator */
const btcOperator = EXPORTS;
const SATOSHI_IN_BTC = 1e8;
@ -7,13 +7,16 @@
util.Sat_to_BTC = value => parseFloat((value / SATOSHI_IN_BTC).toFixed(8));
util.BTC_to_Sat = value => parseInt(value * SATOSHI_IN_BTC);
const checkIfTor = btcOperator.checkIfTor = () => {
return fetch('https://check.torproject.org/api/ip', {
mode: 'no-cors'
})
.then(response => response.json())
.then(result => result.IsTor)
.catch(error => false)
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);

2
btcOperator.min.js vendored

File diff suppressed because one or more lines are too long

View File

@ -1,4 +1,4 @@
(function (EXPORTS) { //floBlockchainAPI v3.1.1
(function (EXPORTS) { //floBlockchainAPI v3.1.4
/* FLO Blockchain Operator to send/receive data from blockchain using API calls via FLO Blockbook*/
'use strict';
const floBlockchainAPI = EXPORTS;
@ -15,22 +15,26 @@
receiverID: floGlobals.adminID
};
floBlockchainAPI.apiURL = DEFAULT.apiURL[DEFAULT.blockchain][0];
const SATOSHI_IN_BTC = 1e8;
const isUndefined = val => typeof val === 'undefined';
const checkIfTor = floBlockchainAPI.checkIfTor = () => {
return fetch('https://check.torproject.org/api/ip', {
mode: 'no-cors'
})
.then(response => response.json())
.then(result => result.IsTor)
.catch(error => false)
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://vl7ni6byqx7rbub5hypxtod5dbfeuhoj5r5exuyl44pspqh2gasjj4qd.onion:9166/')
DEFAULT.apiURL.FLO_TEST.push('http://omwkzk6bd6zuragdqsrhdyzgxzre7yx4vzrou4vzftintzc2dmagp6qd.onion:15017/')
DEFAULT.apiURL.FLO.push('http://xge4kejxl6xs4cad3u3a7dnw7idndlkn3vmyo33t3a4ctk566y65eoad.onion/')
DEFAULT.apiURL.FLO_TEST.push('http://fdjrsde2qhfecvx6fkgmcidwkp34bdek7jo4y2fpqatrhzxtxkk6f4ad.onion/')
}
});
@ -1057,4 +1061,4 @@
})
}
})('object' === typeof module ? module.exports : window.floBlockchainAPI = {});
})('object' === typeof module ? module.exports : window.floBlockchainAPI = {});

File diff suppressed because one or more lines are too long

View File

@ -1,4 +1,4 @@
(function (EXPORTS) { //floCloudAPI v2.4.5
(function (EXPORTS) { //floCloudAPI v2.4.5a
/* FLO Cloud operations to send/request application data*/
'use strict';
const floCloudAPI = EXPORTS;
@ -195,14 +195,24 @@
floCloudAPI.init = function startCloudProcess(nodes) {
return new Promise((resolve, reject) => {
try {
// accept only plain-ish objects
nodes = (nodes && typeof nodes === 'object' && !Array.isArray(nodes)) ? 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));
resolve('Cloud init successful');
} catch (error) {
reject(error);
}
})
}
});
};
Object.defineProperty(floCloudAPI, 'kBucket', {
get: () => kBucket
@ -227,24 +237,27 @@
function ws_activeConnect(snID, reverse = false) {
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');
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)
.then(node => resolve(node))
.catch(error => {
if (reverse)
var nxtNode = kBucket.prevNode(snID);
else
var nxtNode = kBucket.nextNode(snID);
ws_activeConnect(nxtNode, reverse)
.then(node => resolve(node))
.catch(error => reject(error))
})
})
var nxtNode = reverse ? kBucket.prevNode(snID) : kBucket.nextNode(snID);
if (!nxtNode || nxtNode === snID) return reject('Cloud offline'); // nothing else to try
ws_activeConnect(nxtNode, reverse).then(resolve).catch(reject);
});
});
}
function fetch_API(snID, data) {
return new Promise((resolve, reject) => {
if (_inactive.has(snID))
@ -265,25 +278,28 @@
function fetch_ActiveAPI(snID, data, reverse = false) {
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');
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)
.then(result => resolve(result))
.then(resolve)
.catch(error => {
_inactive.add(snID)
if (reverse)
var nxtNode = kBucket.prevNode(snID);
else
var nxtNode = kBucket.nextNode(snID);
fetch_ActiveAPI(nxtNode, data, reverse)
.then(result => resolve(result))
.catch(error => reject(error));
})
})
_inactive.add(snID);
var nxtNode = reverse ? kBucket.prevNode(snID) : kBucket.nextNode(snID);
if (!nxtNode || nxtNode === snID) return reject('Cloud offline'); // nothing else to try
fetch_ActiveAPI(nxtNode, data, reverse).then(resolve).catch(reject);
});
});
}
function singleRequest(floID, data_obj, method = "POST") {
return new Promise((resolve, reject) => {
let data;
@ -374,13 +390,31 @@
const util = floCloudAPI.util = {};
//Updating encoding/Decoding to modern standards
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) {
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 = {}) {
return type + (options.comment ? ':' + options.comment : '') +
@ -468,21 +502,59 @@
function storeGeneral(fk, dataSet) {
try {
console.log(dataSet)
if (typeof generalData[fk] !== "object")
generalData[fk] = {}
for (let vc in dataSet) {
generalData[fk][vc] = dataSet[vc];
if (dataSet[vc].log_time > lastVC[fk])
lastVC[fk] = dataSet[vc].log_time;
if (!dataSet || typeof dataSet !== "object") return;
// Ensure containers exist
if (typeof generalData[fk] !== "object" || generalData[fk] === null)
generalData[fk] = {};
if (typeof lastVC[fk] !== "number")
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 don’t wait on these
compactIDB.writeData("lastVC", lastVC[fk], fk);
compactIDB.writeData("generalData", generalData[fk], fk);
} catch (e) {
console.error(e);
}
}, 50);
} catch (error) {
console.error(error)
console.error(error);
}
}
function objectifier(data) {
if (!Array.isArray(data))
data = [data];
@ -551,7 +623,7 @@
}
//request any data from supernode cloud
const requestApplicationData = floCloudAPI.requestApplicationData = function (type, options = {}) {
const _requestApplicationData = function (type, options = {}) {
return new Promise((resolve, reject) => {
var request = {
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)
//delete data from supernode cloud (received only)
floCloudAPI.deleteApplicationData = function(vectorClocks, options = {}) {
@ -615,7 +698,7 @@
//request the data from cloud for resigning
let req_options = Object.assign({}, options);
req_options.atVectorClock = vectorClock;
requestApplicationData(undefined, req_options).then(result => {
_requestApplicationData(undefined, req_options).then(result => {
if (!result.length)
return reject("Data not found");
let data = result[0];
@ -709,11 +792,11 @@
storeGeneral(fk, d);
options.callback(d, e)
}
requestApplicationData(type, new_options)
_requestApplicationData(type, new_options)
.then(result => resolve(result))
.catch(error => reject(error))
} else {
requestApplicationData(type, options).then(dataSet => {
_requestApplicationData(type, options).then(dataSet => {
storeGeneral(fk, objectifier(dataSet))
resolve(dataSet)
}).catch(error => reject(error))
@ -738,7 +821,7 @@
}
delete options.callback;
}
requestApplicationData(objectName, options).then(dataSet => {
_requestApplicationData(objectName, options).then(dataSet => {
updateObject(objectName, objectifier(dataSet));
delete options.comment;
options.lowerVectorClock = lastVC[objectName] + 1;
@ -746,11 +829,11 @@
if (callback) {
let new_options = Object.create(options);
new_options.callback = callback;
requestApplicationData(objectName, new_options)
_requestApplicationData(objectName, new_options)
.then(result => resolve(result))
.catch(error => reject(error))
} else {
requestApplicationData(objectName, options).then(dataSet => {
_requestApplicationData(objectName, options).then(dataSet => {
updateObject(objectName, objectifier(dataSet))
resolve(appObjects[objectName])
}).catch(error => reject(error))
@ -825,7 +908,7 @@
floCloudAPI.downloadFile = function (vectorClock, options = {}) {
return new Promise((resolve, reject) => {
options.atVectorClock = vectorClock;
requestApplicationData(options.type, options).then(result => {
_requestApplicationData(options.type, options).then(result => {
if (!result.length)
return reject("File not found");
result = result[0];
@ -1103,4 +1186,4 @@
})();
})('object' === typeof module ? module.exports : window.floCloudAPI = {});
})('object' === typeof module ? module.exports : window.floCloudAPI = {});

View File

@ -144,7 +144,7 @@
}
});
var subAdmins, trustedIDs, settings;
var subAdmins = [], trustedIDs = [], settings = {};
Object.defineProperties(floGlobals, {
subAdmins: {
get: () => subAdmins
@ -249,106 +249,154 @@
const startUpFunctions = [];
startUpFunctions.push(function readSupernodeListFromAPI() {
return new Promise((resolve, reject) => {
return new Promise((resolve) => {
if (!startUpOptions.cloud)
return resolve("No cloud for this app");
const CLOUD_KEY = "floCloudAPI#" + floCloudAPI.SNStorageID;
// Fallback: init from cached nodes (never reject)
const initFromCache = (tag) =>
compactIDB.readData("supernodes", CLOUD_KEY, DEFAULT.root)
.then(nodes => {
nodes = nodes || {};
return floCloudAPI.init(nodes)
.then(r => resolve(`${tag} (from cache)\n${r}`))
.catch(() => resolve(`${tag} (cache present, init skipped)`));
})
.catch(() => resolve(`${tag} (no cache)`));
compactIDB.readData("lastTx", CLOUD_KEY, DEFAULT.root).then(lastTx => {
var query_options = { sentOnly: true, pattern: floCloudAPI.SNStorageName };
if (typeof lastTx == 'number') //lastTx is tx count (*backward support)
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') //lastTx is txid of last tx
else if (typeof lastTx === 'string') // last txid
query_options.after = lastTx;
//fetch data from flosight
// 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 (var i = result.data.length - 1; i >= 0; i--) {
var content = JSON.parse(result.data[i])[floCloudAPI.SNStorageName];
for (let sn in content.removeNodes)
delete nodes[sn];
for (let sn in content.newNodes)
nodes[sn] = content.newNodes[sn];
for (let sn in content.updateNodes)
if (sn in nodes) //check if node is listed
nodes[sn].uri = content.updateNodes[sn];
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(_ => {
]).then(() => {
floCloudAPI.init(nodes)
.then(result => resolve("Loaded Supernode list\n" + result))
.catch(error => reject(error))
}).catch(error => reject(error))
}).catch(error => reject(error))
})
}).catch(error => reject(error))
})
.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() {
return new Promise((resolve, reject) => {
return new Promise((resolve) => {
if (!startUpOptions.app_config)
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 };
if (typeof lastTx == 'number') //lastTx is tx count (*backward support)
query_options.ignoreOld = lastTx;
else if (typeof lastTx == 'string') //lastTx is txid of last tx
query_options.after = lastTx;
//fetch data from flosight
// small helper: load cached directives into memory and resolve
const loadFromIDB = (msg) => Promise.all([
compactIDB.readAllData("subAdmins"),
compactIDB.readAllData("trustedIDs"),
compactIDB.readAllData("settings")
]).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 (don’t 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 => {
for (var i = result.data.length - 1; i >= 0; i--) {
var content = JSON.parse(result.data[i])[DEFAULT.application];
if (!content || typeof content !== "object")
continue;
for (let i = result.data.length - 1; i >= 0; i--) {
const content = JSON.parse(result.data[i])[DEFAULT.application];
if (!content || typeof content !== "object") continue;
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]);
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]);
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]);
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]);
if (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 => {
subAdmins = Object.keys(result);
compactIDB.readAllData("trustedIDs").then(result => {
trustedIDs = Object.keys(result);
compactIDB.readAllData("settings").then(result => {
settings = result;
resolve("Read app configuration from blockchain");
})
})
})
})
}).catch(error => reject(error))
})
// persist last item marker (best effort)
compactIDB.writeData("lastTx", result.lastItem, lastKey, DEFAULT.root).catch(() => {});
// load fresh values from IDB into memory and finish
loadFromIDB("Read app configuration from blockchain");
}).catch(() => {
// network failed → boot from cache
loadFromIDB("Read app configuration from local cache (network fail)");
});
}).catch(() => {
// couldn't read lastTx → still boot from cache
loadFromIDB("Read app configuration from local cache (no lastTx)");
});
});
});
startUpFunctions.push(function loadDataFromAppIDB() {
return new Promise((resolve, reject) => {
if (!startUpOptions.cloud)
return resolve("No cloud for this app");
var loadData = ["appObjects", "generalData", "lastVC"]
var promises = []
for (var i = 0; i < loadData.length; i++)
promises[i] = compactIDB.readAllData(loadData[i])
Promise.all(promises).then(results => {
for (var i = 0; i < loadData.length; i++)
floGlobals[loadData[i]] = results[i]
resolve("Loaded Data from app IDB")
}).catch(error => reject(error))
})
const loadData = ["appObjects", "generalData", "lastVC"];
// If cloud is disabled AND no IDB stores are expected, skip early
if (!startUpOptions.cloud && (!initIndexedDB.appObs || Object.keys(initIndexedDB.appObs).length === 0))
return resolve("No cloud and no local data to load");
// Otherwise, read from IDB
Promise.all(loadData.map(item => compactIDB.readAllData(item)))
.then(results => {
for (let i = 0; i < loadData.length; i++)
floGlobals[loadData[i]] = results[i];
resolve("Loaded Data from app IDB");
})
.catch(error => reject(error));
});
});
var keyInput = type => new Promise((resolve, reject) => {
@ -840,4 +888,4 @@
.catch(error => reject(error))
}).catch(error => reject(error))
});
})('object' === typeof module ? module.exports : window.floDapps = {});
})('object' === typeof module ? module.exports : window.floDapps = {});

File diff suppressed because one or more lines are too long

2
floTokenAPI.min.js vendored

File diff suppressed because one or more lines are too long