Skip to content

Instantly share code, notes, and snippets.

@nikkolasg
Last active June 3, 2020 13:24
Show Gist options
  • Save nikkolasg/29a5e5b08f7d69c92ae58e09bcb304f3 to your computer and use it in GitHub Desktop.
Save nikkolasg/29a5e5b08f7d69c92ae58e09bcb304f3 to your computer and use it in GitHub Desktop.
weidghted drand numbers constraint solver
#!/usr/bin/env python3
# requires installation of https://pypi.org/project/python-constraint/
# `pip3 python-constraint` should do it
from constraint import *
import math
import json
# Let X the number of tier 1 nodes.
# Let Y the number of tier 2 nodes.
# Let R be the weight / replication factor of each tier 1 node
# Let T be the threshold of the drand chain.
#
# Usual drand rule:
# - T > (X*R + Y) / 2
# Weight rule:
# - Y < T
# - X*R/2 < T
def weightCheck(t1,t2,rep,thr):
wt1 = t1 * rep
n = wt1 + t2
thrn = math.ceil(thr * n)
enoughT1 = wt1 / 2 < thrn
enoughT2 = t2 < thrn
return enoughT1 and enoughT2
# strongWeightCheck adds another condition is that an attacker must corrupt at
# least two tier 1 nodes + all tier 2 nodes
def strongWeightCheck(t1,t2,rep,thr):
wt1 = t1 * rep
n = wt1 + t2
thrn = math.ceil(thr * n)
enoughT1T2 = t2 + 2 * rep < thrn
return enoughT1T2
def orderSolutions(solutions,priorityKeys):
for key in reversed(priorityKeys):
solutions.sort(key=lambda sol: sol[key])
return solutions
pb = Problem()
# tier 1 nodes
pb.addVariable("tier1",range(2,5))
# tier 2 nodes
pb.addVariable("tier2",range(2,10))
# replication factor
pb.addVariable("weight",range(2,4))
# threshold
pb.addVariable("thr",[0.51,0.55,0.6,0.65])
## This adds the first constraint
pb.addConstraint(lambda t1,t2,rep,thr: weightCheck(t1,t2,rep,thr),("tier1","tier2","weight","thr"))
## This adds the strenghtened constraint - commented to see difference of
## results.
# pb.addConstraint(lambda t1,t2,rep,thr: strongWeightCheck(t1,t2,rep,thr),("tier1","tier2","weight","thr"))
solutions = pb.getSolutions()
for i in solutions:
i["thr"] = math.ceil((i["tier1"] * i["weight"] + i["tier2"]) * i["thr"])
orderSolutions(solutions,["tier1"])
print(json.dumps(solutions,indent=4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment