customizing floDapp for floMessage requirement

This commit is contained in:
sairajzero 2020-03-18 18:46:03 +05:30
parent b46c63d063
commit d4fc6dd999

View File

@ -8278,124 +8278,108 @@ Bitcoin.Util = {
} }
} }
</script> </script>
<script id="floDapps"> <script id="floDapps_customized_for_floMessage">
/* General functions for FLO Dapps*/ /* General functions for FLO Dapps*/
const floDapps = { const floDapps = {
util:{ util: {
appObs:{}, appObs: {},
initIndexedDB: function(){ initIndexedDB: function () {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var storageList = floGlobals.storageList;
var obj = { var obj = {
//general //general
lastTx:{}, lastTx: {},
//supernode (cloud list) //supernode (cloud list)
supernodes:{ supernodes: {
indexes:{ uri:null, pubKey:null } indexes: {
uri: null,
pubKey: null
}
}, },
//login credentials //login credentials
credentials:{}, credentials: {},
//for Dapps //for apps
subAdmins:{}, pubKeys: {},
appObjects:{}, settings: {},
vectorClock:{}, messages: {}
generalData:{},
generalVC:{}
} }
//add other given objectStores
for(o in this.appObs)
if(!(o in obj))
obj[o] = this.appObs[o]
compactIDB.initDB(floGlobals.application, obj).then(result => { compactIDB.initDB(floGlobals.application, obj).then(result => {
resolve("IndexedDB App Storage Initated Successfully") resolve("IndexedDB App Storage Initated Successfully")
}).catch(error => reject(error)); }).catch(error => reject(error));
}) })
}, },
privKeyInput: function(){ privKeyInput: function () {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var privKey = prompt("Enter Private Key: ") var privKey = prompt("Enter Private Key: ")
if(privKey === null) if (privKey === null)
reject(null) reject(null)
else else
resolve(privKey) resolve(privKey)
}) })
}, },
startUpFunctions:{ startUpFunctions: {
readSupernodeListFromAPI: function(){ readSupernodeListFromAPI: function () {
return new Promise((resolve,reject) => { return new Promise((resolve, reject) => {
compactIDB.readData("lastTx",floGlobals.SNStorageID).then(lastTx => { compactIDB.readData("lastTx", floGlobals.SNStorageID).then(lastTx => {
floBlockchainAPI.readData(floGlobals.SNStorageID,{ignoreOld:lastTx,sentOnly:true,pattern:"SuperNodeStorage"}).then(result => { floBlockchainAPI.readData(floGlobals.SNStorageID, {
for(var i=result.data.length-1;i>=0;i--){ ignoreOld: lastTx,
var content = JSON.parse(result.data[i]).SuperNodeStorage; sentOnly: true,
for(sn in content.removeNodes) pattern: "SuperNodeStorage"
compactIDB.removeData("supernodes",sn); }).then(result => {
for(sn in content.addNodes) for (var i = result.data.length - 1; i >= 0; i--) {
compactIDB.writeData("supernodes",content.addNodes[sn],sn); var content = JSON.parse(result.data[i])
.SuperNodeStorage;
for (sn in content.removeNodes)
compactIDB.removeData("supernodes", sn);
for (sn in content.addNodes)
compactIDB.writeData("supernodes", content
.addNodes[sn], sn);
} }
compactIDB.writeData("lastTx",result.totalTxs,floGlobals.SNStorageID); compactIDB.writeData("lastTx", result.totalTxs,
floGlobals.SNStorageID);
compactIDB.readAllData("supernodes").then(result => { compactIDB.readAllData("supernodes").then(result => {
floGlobals.supernodes = result; floGlobals.supernodes = result;
floSupernode.kBucket.launch(Object.keys(floGlobals.supernodes),floGlobals.SNStorageID) floSupernode.kBucket.launch(Object.keys(
.then(result => resolve("Loaded Supernode list\n"+result)) floGlobals.supernodes),
floGlobals.SNStorageID)
.then(result => resolve(
"Loaded Supernode list\n" +
result))
}) })
}) })
}).catch(error => reject(error)) }).catch(error => reject(error))
}) })
}, },
readSubAdminListFromAPI: function(){ loadDataFromIDB: function () {
return new Promise((resolve,reject) => { return new Promise((resolve, reject) => {
compactIDB.readData("lastTx",floGlobals.adminID).then(lastTx => { var loadData = ["pubKeys", "settings"]
floBlockchainAPI.readData(floGlobals.adminID,{ignoreOld:lastTx,sentOnly:true,pattern:floGlobals.application}).then(result => {
for(var i=result.data.length-1;i>=0;i--){
var content = JSON.parse(result.data[i])[floGlobals.application];
if(Array.isArray(content.removeSubAdmin))
for(var 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++)
compactIDB.writeData("subAdmins",true,content.addSubAdmin[k]);
}
compactIDB.writeData("lastTx",result.totalTxs,floGlobals.adminID);
compactIDB.readAllData("subAdmins").then(result => {
floGlobals.subAdmins = Object.keys(result);
resolve("Read subAdmins from blockchain");
})
})
}).catch(error => reject(error))
})
},
loadDataFromIDB: function(){
return new Promise((resolve,reject) => {
var loadData = ["appObjects", "vectorClock", "generalData", "generalVC"]
var promises = [] var promises = []
for(var i = 0; i < loadData.length; i++) for (var i = 0; i < loadData.length; i++)
promises[i] = compactIDB.readAllData(loadData[i]) promises[i] = compactIDB.readAllData(loadData[i])
Promise.all(promises).then(results => { Promise.all(promises).then(results => {
for(var i = 0; i < loadData.length; i++) for (var i = 0; i < loadData.length; i++)
floGlobals[loadData[i]] = results[i] floGlobals[loadData[i]] = results[i]
resolve("Loaded Data from IDB") resolve("Loaded Data from IDB")
}).catch(error => reject(error)) }).catch(error => reject(error))
}) })
}, },
getCredentials: function(){ getCredentials: function () {
var readSharesFromIDB = function(indexArr){ var readSharesFromIDB = function (indexArr) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var promises = [] var promises = []
for(var i = 0; i < indexArr.length; i++) for (var i = 0; i < indexArr.length; i++)
promises.push(compactIDB.readData('credentials', indexArr[i])) promises.push(compactIDB.readData('credentials', indexArr[i]))
Promise.all(promises).then(shares => { Promise.all(promises).then(shares => {
var secret = floCrypto.retrieveShamirSecret(shares) var secret = floCrypto.retrieveShamirSecret(shares)
if(secret) if (secret)
resolve(secret) resolve(secret)
else else
reject("Shares are insufficient or incorrect") reject("Shares are insufficient or incorrect")
@ -8403,38 +8387,39 @@ Bitcoin.Util = {
}) })
} }
var writeSharesToIDB = function(shares, i = 0, resultIndexes = []){ var writeSharesToIDB = function (shares, i = 0, resultIndexes = []) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if(i >= shares.length) if (i >= shares.length)
return resolve(resultIndexes) return resolve(resultIndexes)
var n = floCrypto.randInt(0, 100000) var n = floCrypto.randInt(0, 100000)
compactIDB.addData("credentials", shares[i], n).then(res => { compactIDB.addData("credentials", shares[i], n).then(res => {
resultIndexes.push(n) resultIndexes.push(n)
writeSharesToIDB(shares, i+1, resultIndexes) writeSharesToIDB(shares, i + 1, resultIndexes)
.then(result => resolve(result)) .then(result => resolve(result))
}).catch(error => { }).catch(error => {
writeSharesToIDB(shares, i, resultIndexes) writeSharesToIDB(shares, i, resultIndexes)
.then(result => resolve(result)) .then(result => resolve(result))
}) })
}) })
} }
var getPrivateKeyCredentials = function(){ var getPrivateKeyCredentials = function () {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var indexArr = localStorage.getItem(`${floGlobals.application}#privKey`) var indexArr = localStorage.getItem(`${floGlobals.application}#privKey`)
if(indexArr){ if (indexArr) {
readSharesFromIDB(JSON.parse(indexArr)) readSharesFromIDB(JSON.parse(indexArr))
.then(result => resolve(result)) .then(result => resolve(result))
.catch(error => reject(error)) .catch(error => reject(error))
}else{ } else {
var privKey; var privKey;
floDapps.util.privKeyInput().then(result => { floDapps.util.privKeyInput().then(result => {
try{ try {
if(!result) if (!result)
return reject("Empty Private Key") return reject("Empty Private Key")
var floID = floCrypto.getFloIDfromPubkeyHex(floCrypto.getPubKeyHex(result)) var floID = floCrypto.getFloIDfromPubkeyHex(
floCrypto.getPubKeyHex(result))
privKey = result privKey = result
}catch(error){ } catch (error) {
console.error(error) console.error(error)
return reject("Invalid Private Key") return reject("Invalid Private Key")
} }
@ -8442,17 +8427,26 @@ Bitcoin.Util = {
console.log(error, "Generating Random Keys") console.log(error, "Generating Random Keys")
privKey = floCrypto.generateNewID().privKey privKey = floCrypto.generateNewID().privKey
}).finally(_ => { }).finally(_ => {
var threshold = floCrypto.randInt(10,20) var threshold = floCrypto.randInt(10, 20)
writeSharesToIDB(floCrypto.createShamirsSecretShares(privKey, threshold, threshold)).then(resultIndexes =>{ writeSharesToIDB(floCrypto.createShamirsSecretShares(
//store index keys in localStorage privKey, threshold, threshold)).then(
localStorage.setItem(`${floGlobals.application}#privKey`, JSON.stringify(resultIndexes)) resultIndexes => {
//also add a dummy privatekey to the IDB //store index keys in localStorage
var randomPrivKey = floCrypto.generateNewID().privKey localStorage.setItem(
var randomThreshold = floCrypto.randInt(10,20) `${floGlobals.application}#privKey`,
writeSharesToIDB(floCrypto.createShamirsSecretShares(randomPrivKey, randomThreshold, randomThreshold)) JSON.stringify(resultIndexes))
//resolve private Key //also add a dummy privatekey to the IDB
resolve(privKey) var randomPrivKey = floCrypto
}).catch(error => reject(error)) .generateNewID().privKey
var randomThreshold = floCrypto.randInt(10,
20)
writeSharesToIDB(floCrypto
.createShamirsSecretShares(
randomPrivKey, randomThreshold,
randomThreshold))
//resolve private Key
resolve(privKey)
}).catch(error => reject(error))
}) })
} }
}) })
@ -8467,38 +8461,39 @@ Bitcoin.Util = {
}).catch(error => reject(error)) }).catch(error => reject(error))
}) })
} }
}, },
callStartUpFunction: function(fname){ callStartUpFunction: function (fname) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.startUpFunctions[fname]().then(result => { this.startUpFunctions[fname]().then(result => {
this.callStartUpFunction.completed += 1 this.callStartUpFunction.completed += 1
reactor.dispatchEvent("startUpSuccessLog",`${result}\nCompleted ${this.callStartUpFunction.completed}/${this.callStartUpFunction.total} Startup functions`) reactor.dispatchEvent("startUpSuccessLog",
`${result}\nCompleted ${this.callStartUpFunction.completed}/${this.callStartUpFunction.total} Startup functions`
)
resolve(true) resolve(true)
}).catch(error => { }).catch(error => {
this.callStartUpFunction.failed += 1 this.callStartUpFunction.failed += 1
reactor.dispatchEvent("startUpErrorLog",`${error}\nFailed ${this.callStartUpFunction.failed}/${this.callStartUpFunction.total} Startup functions`) reactor.dispatchEvent("startUpErrorLog",
`${error}\nFailed ${this.callStartUpFunction.failed}/${this.callStartUpFunction.total} Startup functions`
)
reject(false) reject(false)
}) })
}) })
}, },
getFilterString: function(type, options = {}){
var filterStr = JSON.stringify({application: options.application || floGlobals.application, type: type, comment: options.comment})
return filterStr
}
}, },
launchStartUp: function(){ launchStartUp: function () {
return new Promise((resolve,reject) => { return new Promise((resolve, reject) => {
this.util.initIndexedDB().then(log => { this.util.initIndexedDB().then(log => {
console.log(log) console.log(log)
this.util.callStartUpFunction.total = Object.keys(this.util.startUpFunctions).length this.util.callStartUpFunction.total = Object.keys(this.util
.startUpFunctions).length
this.util.callStartUpFunction.completed = 0 this.util.callStartUpFunction.completed = 0
this.util.callStartUpFunction.failed = 0 this.util.callStartUpFunction.failed = 0
var promises = [] var promises = []
for(fn in this.util.startUpFunctions) for (fn in this.util.startUpFunctions)
promises.push(this.util.callStartUpFunction(fn)) promises.push(this.util.callStartUpFunction(fn))
Promise.all(promises) Promise.all(promises)
.then(results => resolve('App Startup finished successful')) .then(results => resolve('App Startup finished successful'))
@ -8506,69 +8501,22 @@ Bitcoin.Util = {
}) })
}) })
}, },
addStartUpFunction: function(fname, fn){
if(fname in this.util.startUpFunctions)
throw(`Function ${fname} already defined`)
this.util.startUpFunctions[fname] = fn;
},
setCustomPrivKeyInput: function(customFn){ setCustomPrivKeyInput: function (customFn) {
this.util.privKeyInput = customFn this.util.privKeyInput = customFn
}, },
setAppObjectStores: function(appObs){ logout: function () {
this.util.appObs = appObs
},
manageSubAdmins(adminPrivKey, addList, rmList){
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if(!Array.isArray(addList)) addList = undefined; compactIDB.deleteDB().then(result => {
if(!Array.isArray(rmList)) rmList = undefined; console.log(result)
var floData = { localStorage.removeItem(`${floGlobals.application}#privKey`)
[floGlobals.application] : { resolve("Logout Sucessful")
addSubAdmin : addList, }).catch(error => {
removeSubAdmin: rmList, console.error(error)
} reject("Logout Unsucessful")
} })
var floID = floCrypto.getFloIDfromPubkeyHex(floCrypto.getPubKeyHex(adminPrivKey))
if(floID != floGlobals.adminID)
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))
}) })
},
clearCredentials: function(){
var indexArr = localStorage.getItem(`${floGlobals.application}#privKey`)
if(!indexArr)
return `privKey credentials not found!`
indexArr = JSON.parse(indexArr)
indexArr.forEach(i => compactIDB.removeData('credentials', i))
localStorage.removeItem(`${floGlobals.application}#privKey`)
return `privKey credentials deleted!`
},
objectDataMapper: function(object, path, data){
var resObject = JSON.parse(JSON.stringify(object))
var pos = resObject;
path.forEach(p => pos = pos[p])
if(Array.isArray(pos)){
pos.push(data)
return resObject
}else
throw('Path is not an Array')
},
getNextGeneralData: function(type, vectorClock, options = {}){
var filter = this.util.getFilterString(type, options)
var filteredResult = []
for(var i = 0; i<floGlobals.generalData[filter].length; i++)
if(floGlobals.generalData[filter][i].vectorClock > vectorClock)
filteredResult.push(floGlobals.generalData[filter][i])
return filteredResult
} }
} }