Skip to content

Instantly share code, notes, and snippets.

@tacyarg
Created August 2, 2018 21:32
Show Gist options
  • Save tacyarg/7eb769c0ec68d9332666d4951ba33d21 to your computer and use it in GitHub Desktop.
Save tacyarg/7eb769c0ec68d9332666d4951ba33d21 to your computer and use it in GitHub Desktop.
provable hash chain generation
var Provable = require('provable')
var lodash = require('lodash')
var assert = require('assert')
var uuid = require('uuid/v4')
//special cofactors
var e = Math.pow(2,52)
var t = 6e-5
var tinv = 1/t
var maxHex = 13
var maxInt = Math.pow(2,maxHex * 4)
module.exports = function(id,resume,upsert){
resume = defaults(resume)
upsert = upsert || function(){}
var provable = Provable(resume,upsert)
function defaults(config){
return lodash.defaults(config,{
id:id,
count:1000,
seed:uuid(),
})
}
function next(){
try{
return provable.next()
}catch(e){
console.log('creating new provable series for',id)
provable = Provable(defaults(),upsert)
return next()
}
}
var methods = { }
methods.new = function(params){
params = lodash.pick(params,['count'])
console.log('creating new provable series for',id,params)
provable = Provable(defaults(),upsert)
}
methods.lastHash = function(){
return provable.last()
}
methods.hashIndex = function(){
return provable.state().index
}
methods.real = function(min,max){
return Provable.toFloat(next(),min,max)
}
methods.bool = function(percent){
return Provable.toBool(next(),percent)
}
methods.integer = function(min,max){
var outcome = Provable.toFloat(next())
min = min || 0
max = max || Math.pow(2,32)
var range = max - min
return parseInt(outcome * range + min)
}
methods.shouldBust = function(hash,mod){
if(mod == null || mod <= 0) return false
if(hash == null) return false
// We will read in 4 hex at a time, but the first chunk might be a bit smaller
// So ABCDEFGHIJ should be chunked like AB CDEF GHIJ
var val = 0;
var o = hash.length % 4;
for (var i = o > 0 ? o - 4 : 0; i < hash.length; i += 4) {
val = ((val << 16) + parseInt(hash.substring(i, i+4), 16)) % mod;
}
return val === 0;
}
methods.nextMultiplier = function(instabustChance){
var hash = next()
var fraction = parseInt(1000/(instabustChance*1000))
if(methods.shouldBust(hash,fraction)){
return 0
}
var number = Provable.toInt(hash,maxHex)
return Math.floor((100 * e - number) / (e - number))/100
}
methods.index = function(){
return provable.state().index
}
return methods
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment