Added webAppServer features

This commit is contained in:
Vivek Teega 2020-09-01 09:54:50 +05:30
parent 1396012858
commit 02ae6936d4

View File

@ -504,11 +504,13 @@
//for cloud apps
subAdmins: [],
webAppURL: "167.172.219.249:8368",
application: "TestApp",
vectorClock: {},
appObjects: {},
generalData: {},
generalVC: {}
}
</script>
@ -663,7 +665,7 @@
for (var bytes = [], i = 0, imod4 = 0; i < base64.length; imod4 = ++i % 4) {
if (imod4 == 0) continue;
bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & (Math.pow(2, -2 * imod4 +
8) - 1)) << (imod4 * 2)) |
8) - 1)) << (imod4 * 2)) |
(base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)));
}
@ -735,7 +737,7 @@
var digestbytes = util.wordsToBytes(SHA1._sha1(message));
return options && options.asBytes ? digestbytes :
options && options.asString ? Binary.bytesToString(digestbytes) :
util.bytesToHex(digestbytes);
util.bytesToHex(digestbytes);
};
// The core
@ -776,9 +778,9 @@
var t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + (
j < 20 ? (H1 & H2 | ~H1 & H3) + 1518500249 :
j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 :
j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 :
(H1 ^ H2 ^ H3) - 899497514);
j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 :
j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 :
(H1 ^ H2 ^ H3) - 899497514);
H4 = H3;
H3 = H2;
@ -852,7 +854,7 @@
return options && options.asBytes ? hmacbytes :
options && options.asString ? Binary.bytesToString(hmacbytes) :
util.bytesToHex(hmacbytes);
util.bytesToHex(hmacbytes);
};
@ -925,8 +927,8 @@
for (var b = b.replace(/[^A-Z0-9+\/]/ig, ""), a = [], c = 0, e = 0; c < b.length; e = ++c %
4) e != 0 && a.push(("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
.indexOf(b.charAt(c - 1)) & Math.pow(2, -2 * e + 8) - 1) << e * 2 |
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(b.charAt(
c)) >>> 6 - e * 2);
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(b.charAt(
c)) >>> 6 - e * 2);
return a
}
},
@ -993,7 +995,7 @@
for (h = 0; h < 64; h++) {
h < 16 ? d[h] = e[h + t] : (l = d[h - 15], j = d[h - 2], d[h] = ((l << 25 | l >>> 7) ^
(l << 14 | l >>> 18) ^ l >>> 3) + (d[h - 7] >>> 0) + ((j << 15 | j >>> 17) ^
(j << 13 | j >>> 19) ^ j >>> 10) + (d[h - 16] >>> 0));
(j << 13 | j >>> 19) ^ j >>> 10) + (d[h - 16] >>> 0));
j = f & g ^ f & m ^ g & m;
var u = (f << 30 | f >>> 2) ^ (f << 19 | f >>> 13) ^ (f << 10 | f >>> 22);
l = (s >>> 0) + ((i << 26 | i >>> 6) ^ (i << 21 | i >>> 11) ^ (i << 7 | i >>> 25)) +
@ -1059,7 +1061,7 @@
(function () {
// Constructor function of Global SecureRandom object
var sr = window.SecureRandom = function () {};
var sr = window.SecureRandom = function () { };
// Properties
sr.state;
@ -1469,7 +1471,7 @@
if (a != null)
if ("number" == typeof a) this.fromNumber(a, b, c);
else if (b == null && "string" != typeof a) this.fromString(a, 256);
else this.fromString(a, b);
else this.fromString(a, b);
};
// Bits per digit
@ -2935,7 +2937,7 @@
// A "null" reducer
var NullExp = window.NullExp = function NullExp() {}
var NullExp = window.NullExp = function NullExp() { }
NullExp.prototype.convert = function (x) {
return x;
};
@ -3026,7 +3028,7 @@
(function () {
// Constructor function of Global EllipticCurve object
var ec = window.EllipticCurve = function () {};
var ec = window.EllipticCurve = function () { };
// ----------------
// ECFieldElementFp constructor
@ -3112,7 +3114,7 @@
P = new BigInteger(this.q.bitLength(), rand);
}
while (P.compareTo(this.q) >= 0 || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent,
this.q).equals(qMinusOne)));
this.q).equals(qMinusOne)));
var result = ec.FieldElementFp.fastLucasSequence(this.q, P, Q, k);
@ -3173,8 +3175,8 @@
// No-operation padding, used for stream ciphers
C_pad.NoPadding = {
pad: function (cipher, message) {},
unpad: function (cipher, message) {}
pad: function (cipher, message) { },
unpad: function (cipher, message) { }
};
// Zero Padding.
@ -3596,7 +3598,7 @@
return options && options.asBytes ? derivedKeyBytes :
options && options.asString ? Binary.bytesToString(derivedKeyBytes) :
util.bytesToHex(derivedKeyBytes);
util.bytesToHex(derivedKeyBytes);
};
@ -4063,11 +4065,11 @@
// Inner state
var state = [
[],
[],
[],
[]
],
[],
[],
[],
[]
],
keylength,
nrounds,
keyschedule;
@ -4093,8 +4095,8 @@
// Convert to bytes if message is a string
m = (
message.constructor == String ?
UTF8.stringToBytes(message) :
message
UTF8.stringToBytes(message) :
message
),
// Generate random IV
@ -4103,12 +4105,12 @@
// Generate key
k = (
password.constructor == String ?
// Derive key from pass-phrase
C.PBKDF2(password, iv, 32, {
asBytes: true
}) :
// else, assume byte array representing cryptographic key
password
// Derive key from pass-phrase
C.PBKDF2(password, iv, 32, {
asBytes: true
}) :
// else, assume byte array representing cryptographic key
password
);
// Encrypt
@ -4136,8 +4138,8 @@
// Convert to bytes if ciphertext is a string
c = (
ciphertext.constructor == String ?
util.base64ToBytes(ciphertext) :
ciphertext
util.base64ToBytes(ciphertext) :
ciphertext
),
// Separate IV and message
@ -4146,12 +4148,12 @@
// Generate key
k = (
password.constructor == String ?
// Derive key from pass-phrase
C.PBKDF2(password, iv, 32, {
asBytes: true
}) :
// else, assume byte array representing cryptographic key
password
// Derive key from pass-phrase
C.PBKDF2(password, iv, 32, {
asBytes: true
}) :
// else, assume byte array representing cryptographic key
password
);
// Decrypt
@ -4972,7 +4974,7 @@
//bitTrx.js
(function () {
var bitjs = window.bitjs = function () {};
var bitjs = window.bitjs = function () { };
/* public vars */
bitjs.pub = 0x23; // flochange - changed the prefix to FLO Mainnet PublicKey Prefix 0x23
@ -5994,7 +5996,7 @@
if (pubkey.getBitcoinAddress().toString() == address) {
return i;
}
} catch (e) {}
} catch (e) { }
}
throw "Unable to find valid recovery factor";
}
@ -6100,8 +6102,8 @@
// 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.
if (((floGlobals.blockchain == "FLO") &&
/^R[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(
input)) ||
/^R[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(
input)) ||
((floGlobals.blockchain == "FLO_TEST") &&
/^c[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(
input))) {
@ -6531,7 +6533,7 @@
});
},
// duck typing method
hasMethods: function (obj /*, method list as strings */ ) {
hasMethods: function (obj /*, method list as strings */) {
var i = 1,
methodName;
while ((methodName = arguments[i++])) {
@ -6547,7 +6549,7 @@
(function (ellipticCurveType) {
//Defining Elliptic Encryption Object
var ellipticEncryption = window.ellipticCurveEncryption = function () {};
var ellipticEncryption = window.ellipticCurveEncryption = function () { };
ellipticEncryption.rng = new SecureRandom();
@ -6722,7 +6724,7 @@
function init(bits) {
if (bits && (typeof bits !== 'number' || bits % 1 !== 0 || bits < defaults.minBits || bits >
defaults.maxBits)) {
defaults.maxBits)) {
throw new Error('Number of bits must be an integer between ' + defaults.minBits + ' and ' +
defaults.maxBits + ', inclusive.')
}
@ -6786,7 +6788,7 @@
// node.js crypto.randomBytes()
if (typeof require === 'function' && (crypto = require('crypto')) && (randomBits = crypto[
'randomBytes'])) {
'randomBytes'])) {
return function (bits) {
var bytes = Math.ceil(bits / 8),
str = null;
@ -6800,7 +6802,7 @@
// browsers with window.crypto.getRandomValues()
if (global['crypto'] && typeof global['crypto']['getRandomValues'] === 'function' && typeof global[
'Uint32Array'] === 'function') {
'Uint32Array'] === 'function') {
crypto = global['crypto'];
return function (bits) {
var elems = Math.ceil(bits / 32),
@ -6857,7 +6859,7 @@
// test the RNG (5 times)
if (typeof rng !== 'function' || typeof rng(config.bits) !== 'string' || !parseInt(rng(config.bits),
2) || rng(config.bits).length > config.bits || rng(config.bits).length < config.bits) {
2) || rng(config.bits).length > config.bits || rng(config.bits).length < config.bits) {
throw new Error(
"Random number generator is invalid. Supply an RNG of the form function(bits){} that returns a string containing 'bits' number of random 1's and 0's."
)
@ -7014,7 +7016,7 @@
var bits = parseInt(share[0], 36);
if (bits && (typeof bits !== 'number' || bits % 1 !== 0 || bits < defaults.minBits || bits >
defaults.maxBits)) {
defaults.maxBits)) {
throw new Error('Number of bits must be an integer between ' + defaults.minBits + ' and ' +
defaults.maxBits + ', inclusive.')
}
@ -7132,13 +7134,13 @@
continue;
}
if (at === x[
j]) { // happens when computing a share that is in the list of shares used to compute it
j]) { // happens when computing a share that is in the list of shares used to compute it
product = -
1; // fix for a zero product term, after which the sum should be sum^0 = sum, not sum^1
break;
}
product = (product + config.logs[at ^ x[j]] - config.logs[x[i] ^ x[j]] + config
.max /* to make sure it's not negative */ ) %
.max /* to make sure it's not negative */) %
config.max;
}
@ -7739,7 +7741,7 @@
var receiverDerivedKey = this.util.deriveReceiverSharedKey(data.senderPublicKeyString,
receiverECKeyData
.privateKey);
.privateKey);
let receiverKey = receiverDerivedKey.XValue + receiverDerivedKey.YValue;
let decryptMsg = Crypto.AES.decrypt(data.secret, receiverKey);
@ -8100,7 +8102,7 @@
invalids.InvalidSenderPrivKeys.push(key);
else {
if (typeof senderPrivKeys[key] !== 'number' || senderPrivKeys[
key] <= 0)
key] <= 0)
invalids.InvalidSenderAmountFor.push(key)
else
inputVal += senderPrivKeys[key];
@ -8155,7 +8157,7 @@
for (let floID in senders) {
balance[floID] = parseFloat(results.shift());
if (isNaN(balance[floID]) || (preserveRatio && balance[floID] <=
totalFee) || (!preserveRatio && balance[floID] < senders[floID]
totalFee) || (!preserveRatio && balance[floID] < senders[floID]
.coins + dividedFee))
insufficient.push(floID)
totalBalance += balance[floID];
@ -8288,13 +8290,13 @@
continue;
if (options.pattern && !response.items[i].floData
.startsWith(options.pattern, 0) && !response.items[i]
.floData.startsWith(options.pattern, 2))
.floData.startsWith(options.pattern, 2))
continue;
if (options.contains && !response.items[i].floData.includes(
options.contains))
options.contains))
continue;
if (options.filter && !options.filter(response.items[i]
.floData))
.floData))
continue;
filteredData.push(response.items[i].floData);
}
@ -8303,8 +8305,8 @@
data: filteredData
});
}).catch(error => {
reject(error);
});
reject(error);
});
}).catch(error => {
reject(error);
});
@ -8978,7 +8980,7 @@
var db = event.target.result;
for (let obs in objectStores) {
var objectStore = db.createObjectStore(obs, objectStores[obs].options ||
{});
{});
if (objectStores[obs].indexes && typeof objectStores[obs].indexes ===
'object')
for (let i in objectStores[obs].indexes)
@ -9404,8 +9406,8 @@
floGlobals.supernodes = result;
floSupernode.kBucket.launch(Object.keys(
floGlobals.supernodes),
floGlobals.SNStorageID)
floGlobals.supernodes),
floGlobals.SNStorageID)
.then(result => resolve(
"Loaded Supernode list\n" +
result))
@ -9534,23 +9536,23 @@
var threshold = floCrypto.randInt(10, 20)
writeSharesToIDB(floCrypto.createShamirsSecretShares(
privKey, threshold, threshold)).then(
resultIndexes => {
//store index keys in localStorage
localStorage.setItem(
`${floGlobals.application}#privKey`,
JSON.stringify(resultIndexes))
//also add a dummy privatekey to the IDB
var randomPrivKey = floCrypto
.generateNewID().privKey
var randomThreshold = floCrypto.randInt(10,
20)
writeSharesToIDB(floCrypto
.createShamirsSecretShares(
randomPrivKey, randomThreshold,
randomThreshold))
//resolve private Key
resolve(privKey)
}).catch(error => reject(error))
resultIndexes => {
//store index keys in localStorage
localStorage.setItem(
`${floGlobals.application}#privKey`,
JSON.stringify(resultIndexes))
//also add a dummy privatekey to the IDB
var randomPrivKey = floCrypto
.generateNewID().privKey
var randomThreshold = floCrypto.randInt(10,
20)
writeSharesToIDB(floCrypto
.createShamirsSecretShares(
randomPrivKey, randomThreshold,
randomThreshold))
//resolve private Key
resolve(privKey)
}).catch(error => reject(error))
})
}
})
@ -9666,8 +9668,8 @@
reject('Access Denied for Admin privilege')
else
floBlockchainAPI.writeData(floID, JSON.stringify(floData), adminPrivKey)
.then(result => resolve(['Updated SubAdmin List', result]))
.catch(error => reject(error))
.then(result => resolve(['Updated SubAdmin List', result]))
.catch(error => reject(error))
})
},
@ -9728,27 +9730,74 @@
reactor.addEventListener("startUpErrorLog", log => console.error(log))
</script>
<script>
// helper functions
(async () => {
let repourl = "https://api.github.com/repos/ranchimall/articles/contents"
let repocontent = null
window.articles = {}
window.parsedarticles = {}
<script id="webAppClient">
//Add this to the client script to request data from floWebappServer
const webAppClient = {
util: {
repocontent = await (await fetch(repourl)).json();
for (let i = 0; i < repocontent.length; i++) {
articlehtml = await (await fetch(repocontent[i]["download_url"])).text()
if (repocontent[i]['name'].slice(-5, repocontent[i]['name'].length) == '.html' && repocontent[i]['name'].slice(0, -5) != 'index') {
articles[repocontent[i]['name'].slice(0, repocontent[i]['name'].length - 5)] = articlehtml
requestData(request = []) {
return new Promise((resolve, reject) => {
var websocket = new WebSocket("ws://" + floGlobals.webAppURL + "/ws");
websocket.onmessage = (evt => {
if (evt.data == '$+') {
websocket.send(`?${JSON.stringify(request)}`);
} else if (evt.data == '$-') {
reject(`webApp not available`)
websocket.close()
} else {
resolve(JSON.parse(evt.data));
websocket.close();
}
})
websocket.onerror = (evt) => {
reject(`webApp server not found`)
};
})
}
}
},
parseArticles(articles)
renderColumns(parsedarticles)
})();
requestGeneralData: function (type, vectorClock = '0') {
if (typeof vectorClock !== 'string')
vectorClock.toString()
return new Promise((resolve, reject) => {
this.util.requestData([floGlobals.application, 'generalData', type, vectorClock])
.then(
result => {
if (result[0])
resolve(result[1])
else
reject(result[1])
}).catch(error => reject(error))
})
},
requestObjectData: function (keyPath) {
return new Promise((resolve, reject) => {
this.util.requestData([floGlobals.application, 'appObjects'].concat(keyPath)).then(
result => {
if (result[0])
resolve(result[1])
else
reject(result[1])
}).catch(error => reject(error))
})
},
requestSubAdminList: function () {
return new Promise((resolve, reject) => {
this.util.requestData([floGlobals.application, 'subAdmins']).then(
result => {
if (result[0])
resolve(result[1])
else
reject(result[1])
}).catch(error => reject(error))
})
}
}
</script>
<script id="onLoadStartUp">
async function fetchArticleDetails() {
let applicants = await floCloudAPI.requestGeneralData('test')
@ -9792,9 +9841,10 @@
numberOfColumns = Object.keys(parsedarticles).length
let columns = document.getElementById('columnsmain')
let parsedArticlesKeys = Object.keys(parsedarticles)
let map_articlekey_column = {}
for (let i = 0; i < parsedArticlesKeys.length; i++) {
columnhtml = `<div class="column" id="column${i+1}" data-articlekey="${parsedArticlesKeys[i]}">
columnhtml = `<div class="column" id="column${i + 1}" data-articlekey="${parsedArticlesKeys[i]}">
<div class="head">
<span class="headline hl3">${parsedarticles[parsedArticlesKeys[i]].title}</span>
<p><span class="headline hl4">${parsedarticles[parsedArticlesKeys[i]].subtitle}</span></p>
@ -9803,14 +9853,17 @@
<span><a href='./${parsedArticlesKeys[i]}.html'>Read article
<i class="fa fa-angle-double-right" aria-hidden="true"></i>
</a>
<span style="float:right"><span id="column${i+1}_count"></span><i class="fa fa-thumbs-o-up" aria-hidden="true" style="padding-left:0.5rem; cursor:pointer" id="column${i+1}_thumbs" onclick="clickProcess(this)"></i></span>
<span style="float:right"><span id="column${i + 1}_count"></span><i class="fa fa-thumbs-o-up" aria-hidden="true" style="padding-left:0.5rem; cursor:pointer" id="column${i + 1}_thumbs" onclick="clickProcess(this)"></i></span>
<span>
</div>`
//columns.append(columnhtml)
columns.innerHTML += columnhtml
map_articlekey_column[parsedArticlesKeys[i]] = `column${i + 1}`
}
return map_articlekey_column
}
function switchtoArticle(element) {
@ -9864,9 +9917,8 @@
}
});
</script>
<script id="onLoadStartUp">
function updateVotes(articles_votesmapping, map_articlekey_column) {
var articleKeys = Object.keys(map_articlekey_column)
@ -9878,6 +9930,46 @@
}
}
let repourl = "https://api.github.com/repos/ranchimall/articles/contents"
Promise.all([fetch(repourl), webAppClient.requestGeneralData('test')]).then(async (values) => {
let repocontent = null
window.articles = {}
window.parsedarticles = {}
repocontent = await values[0].json()
for (let i = 0; i < repocontent.length; i++) {
articlehtml = await (await fetch(repocontent[i]["download_url"])).text()
if (repocontent[i]['name'].slice(-5, repocontent[i]['name'].length) == '.html' && repocontent[i]['name'].slice(0, -5) != 'index') {
articles[repocontent[i]['name'].slice(0, repocontent[i]['name'].length - 5)] = articlehtml
}
}
parseArticles(articles)
let map_articlekey_column = renderColumns(parsedarticles)
let articleInfo = values[1]
let articles_votesmapping = {}
for (let i = 0; i < articleInfo.length; i++) {
let article_message = JSON.parse(articleInfo[i].message)
if (!(article_message.articlekey in articles_votesmapping)) {
articles_votesmapping[article_message.articlekey] = 1
} else {
articles_votesmapping[article_message.articlekey]++
}
}
updateVotes(articles_votesmapping, map_articlekey_column)
})
let myCustomLogin = function () {
return new Promise((resolve, reject) => {
@ -9893,10 +9985,9 @@
//floDapps.addStartUpFunction('Sample', Promised Function)
//floDapps.setAppObjectStores({sampleObs1:{}, sampleObs2:{options{autoIncrement:true, keyPath:'SampleKey'}, Indexes:{sampleIndex:{}}}})
floDapps.setCustomPrivKeyInput(myCustomLogin);
floCloudAPI.requestGeneralData('test');
floDapps.launchStartUp().then(result => {
document.getElementById("login-button").style.display = 'none'
document.getElementById("user-button").style.display = 'initial'
console.log(result)
@ -9943,9 +10034,9 @@
updateVotes(articles_votesmapping, map_articlekey_column)
});
}).catch(error => console.error(error))
}
</script>
</html>