adding floDapps std_Op

This std_op contains functions for FLO Dapp startup and other useful functions for FLO Dapps
This commit is contained in:
sairajzero 2019-12-19 22:03:53 +05:30
parent e42a972f12
commit 5a2b6250ca

View File

@ -36,7 +36,7 @@
</head>
<body>
<body onload="onLoadStartUp()">
use console
<script id="init_lib">
@ -7007,5 +7007,271 @@
}
}
</script>
<script id="floDapps">
const floDapps = {
util:{
appObs:{},
initIndexedDB: function(){
return new Promise((resolve, reject) => {
var storageList = floGlobals.storageList;
var obj = {
//general
lastTx:{},
//supernode (cloud list)
supernodes:{
indexes:{ uri:null, pubKey:null }
},
//login credentials
credentials:{},
//for Dapps
subAdmins:{},
appObjects:{},
vectorClocks:{},
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 => {
resolve("Initiated supernode storage")
}).catch(error => reject(error));
})
},
startUpFunctions:{
readSupernodeListFromAPI: function(){
return new Promise((resolve,reject) => {
compactIDB.readData("lastTx",floGlobals.SNStorageID).then(lastTx => {
floBlockchainAPI.readData(floGlobals.SNStorageID,{ignoreOld:lastTx,sentOnly:true,pattern:"SuperNodeStorage"}).then(result => {
for(var i=result.data.length-1;i>=0;i--){
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.readAllData("supernodes").then(result => {
floGlobals.supernodes = result;
floSupernode.kBucket.launch(Object.keys(floGlobals.supernodes),floGlobals.SNStorageID)
.then(result => resolve("Loaded Supernode list\n"+result))
})
})
}).catch(error => reject(error))
})
},
readSubAdminListFromAPI: function(){
return new Promise((resolve,reject) => {
compactIDB.readData("lastTx",floGlobals.adminID).then(lastTx => {
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", "vectorClocks", "generalData", "generalVC"]
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 IDB")
}).catch(error => reject(error))
})
},
getCredentials: function(){
var readSharesFromIDB = function(indexArr){
return new Promise((resolve, reject) => {
var promises = []
for(var i = 0; i < indexArr.length; i++)
promises.push(compactIDB.readData('credentials', indexArr[i]))
Promise.all(promises).then(shares => {
var secret = floCrypto.retrieveShamirSecret(shares)
if(secret)
resolve(secret)
else
reject("Shares are insufficient or incorrect")
}).catch(error => reject(error))
})
}
var writeSharesToIDB = function(shares, i = 0, resultIndexes = []){
return new Promise((resolve, reject) => {
if(i >= shares.length)
return resolve(resultIndexes)
var n = floCrypto.randInt(0, 100000)
compactIDB.addData("credentials", shares[i], n).then(res => {
resultIndexes.push(n)
writeSharesToIDB(shares, i+1, resultIndexes)
.then(result => resolve(result))
}).catch(error => {
writeSharesToIDB(shares, i, resultIndexes)
.then(result => resolve(result))
})
})
}
var getPrivateKeyCredentials = function(){
return new Promise((resolve, reject) => {
var indexArr = localStorage.getItem("privKey")
if(indexArr){
readSharesFromIDB(JSON.parse(indexArr))
.then(result => resolve(result))
.catch(error => reject(error))
}else{
try{
var privKey = prompt("Enter Private Key: ")
if(!privKey)
return reject("Empty Private Key")
var floID = floCrypto.getFloIDfromPubkeyHex(floCrypto.getPubKeyHex(privKey))
console.log(floID)
}catch(error){
console.error(error)
return reject("Invalid Private Key")
}
var threshold = floCrypto.randInt(10,20)
writeSharesToIDB(floCrypto.createShamirsSecretShares(privKey, threshold, threshold)).then(resultIndexes =>{
//store index keys in localStorage
console.log(resultIndexes)
localStorage.setItem("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))
}
})
}
return new Promise((resolve, reject) => {
getPrivateKeyCredentials().then(privKey => {
myPrivKey = privKey
myPubKey = floCrypto.getPubKeyHex(myPrivKey)
myFloID = floCrypto.getFloIDfromPubkeyHex(myPubKey)
resolve('Login Credentials loaded successful')
}).catch(error => reject(error))
})
}
},
callStartUpFunction: function(fname){
return new Promise((resolve, reject) => {
this.startUpFunctions[fname]().then(result => {
console.log(result)
this.callStartUpFunction.completed += 1
console.log(`Completed ${this.callStartUpFunction.completed}/${this.callStartUpFunction.total} Startup functions`)
resolve(true)
}).catch(error => {
console.error(error)
console.log(`Failed ${this.callStartUpFunction.failed}/${this.callStartUpFunction.total} Startup functions`)
reject(false)
})
})
},
getFilterString: function(type, options = {}){
var filterStr = JSON.stringify({application: options.application || floGlobals.application, type: type, comment: options.comment})
return filterStr
}
},
launchStartUp: function(){
return new Promise((resolve,reject) => {
this.util.initIndexedDB().then(log => {
console.log(log)
this.util.callStartUpFunction.total = Object.keys(this.util.startUpFunctions).length
this.util.callStartUpFunction.completed = 0
this.util.callStartUpFunction.failed = 0
var promises = []
for(fn in this.util.startUpFunctions)
promises.push(callStartUpFunction(fn))
Promise.all(promises)
.then(results => resolve('App Startup finished successful'))
.catch(errors => reject('App StartUp failed'))
})
})
},
addStartUpFunction: function(fname, fn){
if(fname in this.util.startUpFunctions)
throw(`Function ${fname} already defined`)
this.util.startUpFunctions[fname] = fn;
},
setAppObjectStores: function(appObs){
this.util.appObs = appObs
},
clearCredentials: function(){
var indexArr = localStorage.getItem("privKey")
if(!indexArr)
return `privKey credentials not found!`
indexArr = JSON.parse(indexArr)
indexArr.forEach(i => compactIDB.removeData('credentials', i))
localStorage.removeItem("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
}
}
function onLoadStartUp() {
//addStartUpFunction('Sample', Promised Function)
//setAppObjectStores({sampleObs1:{}, sampleObs2:{options{autoIncrement:true, keyPath:'SampleKey'}, Indexes:{sampleIndex:{}}}})
floDapps.launchStartUp().then(result => {
console.log(result)
alert(`Welcome FLO_ID: ${myFloID}`)
})
}
</script>
</body>
</html>