Commit ff207fdc authored by THAKARE AKSHAY HARIBHAU's avatar THAKARE AKSHAY HARIBHAU

Merge branch 'Nalgo' into 'algorand'

Nalgo

See merge request !6
parents 10a0b11f 9787ac65
......@@ -4,8 +4,10 @@ import csv
from Node import Node
from OverlayNode import OverlayNode
import logging
import random
from numpy.random import randint
logger = logging.getLogger(__name__)
import numpy as np
......@@ -14,6 +16,7 @@ class Network():
self.nodes = {}#{1 : Node(1),2:Node(2)}
self.links = {} #{(1,2):Link(1-2),(2,1):Link(2,1),(3,2):Link(3*2)} linkID = tuple(1,2)
self.networkClockTime = 0
self.pk_weight_map = {}
def setupNetwork(self):
'''
......@@ -27,12 +30,16 @@ class Network():
:return:
'''
w = randint(1, 51, 4) # 51 is excluded - range (1,50)
self.badaW = np.sum(w)
i = 0
with open('Nodes.dat', 'r') as f:
reader = csv.reader(f)
for row in reader:
node = row[0] # tuple of a link
self.nodes.update({node:OverlayNode(node,self)})
node = row[0] # NOde id
xnode = {node:OverlayNode(node,self,w[i])}
self.pk_weight_map.update({xnode[node].pk:w[i]})
self.nodes.update(xnode)#added node to network
# print(self.nodes.get('1')) #keys are strings
......
......@@ -3,19 +3,19 @@ import logging
import Utility
class Node(SystemEntity):
def __init__(self,id,network):
def __init__(self,id,network,weight):
SystemEntity.__init__(self,network)
self.logger = logging.getLogger(__name__ + "-" + str(id))
self.id = id
self.weight = weight
self.adjacentNodes = []
self.messageQueue = []
self.sk, self.pk = Utility.genratePublicPrivateKey()
self.sk,self.pk = Utility.genratePublicPrivateKey()
'''make sure methods included here are not overriddenn'''
self.commands={"sendMessage":self.sendMessage,
"nextOn":self.nextOn
}
......@@ -59,6 +59,9 @@ class Node(SystemEntity):
payload.pop(0) # removed source header
payload.pop(0) #removed destination header
def nextOn(self,time,generator):
next(generator[0])
def startNodeLifeCycle(self):
pass
......@@ -87,10 +90,15 @@ class Node(SystemEntity):
tasks = self.todoList.pop(time)
for task in tasks:
command = self.commands.get(task[0])
command(time,task[1:])
out = command(time,task[1:])
if out and out[0] == "resume":
self.logger.info("resume has been called")
self.todoList[time+1].append(("nextOn", self.startNodeLifeCycleGenerator,))
except KeyError as ke:
# not task pending at this time
pass
except StopIteration as si:
pass
......@@ -108,4 +116,3 @@ if __name__ == '__main__':
from Node import Node
import logging
import Utility
import hashlib
genesisBlock = "I am the first block"
class OverlayNode(Node):
def __init__(self,id,network):
Node.__init__(self,id,network)
def __init__(self,id,network,weight):
Node.__init__(self,id,network,weight)
self.startNodeLifeCycleGenerator = self.startNodeLifeCycle()
self.commands.update({})
def processMessage(self,time,payload):
......@@ -12,9 +17,52 @@ class OverlayNode(Node):
def startNodeLifeCycle(self):
'''THis is monolithic algorand algorithm for a NOde'''
self.logger.info("Life cycle started")
while True:
#increment round number
# Checking if I am a Block Propser
previousHash = hashlib.sha256(genesisBlock.encode('utf-8')).hexdigest()
currentRound = 0
step = 0
blockHeight = 0
seed = ( previousHash,currentRound,blockHeight )
roleCount = 20
role = "BLOCK_PROPOSER"
w = self.weight
badaW = 100
hash, proof, j = Utility.sortition(self.sk,seed,roleCount, role, w, self.network.badaW, self.pk)
print("I am the mighty J =",j)
if j > 0 :
min_sha_priority = None
# min_sub_user_index = None
# msg_to_broadcast = ( currentRound, hash , min_sub_user_index , min_sha_priority )
print(w)
print(range(w))
for sub_user_index in range(w):
input_to_SHA256 = (hash , sub_user_index,) # TODO : can concatenation means this
sha256_hash = hashlib.sha256((str(input_to_SHA256)).encode('utf-8')).hexdigest()
print(sha256_hash)
if not min_sha_priority :
min_sha_priority = sha256_hash
min_sub_user_index = sub_user_index
if sha256_hash < min_sha_priority:
min_sha_priority = sha256_hash
min_sub_user_index = sub_user_index
msg_to_broadcast = ( currentRound, hash , min_sub_user_index , min_sha_priority )
print(msg_to_broadcast)
self.logger.info(msg_to_broadcast)
print("i am before yield 1",self.id)
yield "resume"
print("i am before yield 2", self.id)
yield
'''
TODo check if node is selected as BLOCK_PROPOSER
if yes
......
#Algorand
* Dsicrete Event Simulator
* Gossip Protocol
* Installation
`pip3 install -r requirements.txt `
* Setup
* Requirements
* How to run
### Nilesh doubts:
\ No newline at end of file
......@@ -18,6 +18,8 @@ def populateTodolist(net):
instruction = row[0].split() # tuple of a link
node = network.nodes.get(instruction[0])
node.todoList[instruction[1]].append(tuple(instruction[2:]))
for id, node in network.nodes.items():
node.todoList['0'].append(("nextOn",node.startNodeLifeCycleGenerator,))
for id,node in network.nodes.items():
logger.info(id +" : "+str(node.todoList))
......@@ -38,7 +40,7 @@ def simulateNetwork(net):
if __name__ == '__main__':
logging.basicConfig(filename='TestCases.log', level=logging.INFO)
# populateTodolist()
# populateTodolist(None)
simulateNetwork(None)
pass
from ecdsa import SigningKey,SECP256k1
from ecdsa.keys import BadSignatureError
from numpy.random import randint
import numpy as np
import binascii
import random
......@@ -49,7 +51,7 @@ def verifyVRF(pk,hash,proof,seed):
def sortition(sk,seed,rolecount,role,w,badaW,pk):
'''
:param sk: secrete key
:param sk: secret key
:param seed:
:param rolecount: tou
:param role:
......@@ -133,23 +135,23 @@ def verifySort(pk,hash,proof,seed,rolecount,role,w,badaW):
return j
def computeRange():
badaW=10
lastValue = 0;
p = 0.5
x = 0.0023
j = 0
if (x<=stats.binom.pmf(0, badaW, p)):
j = 0
else :
for k in range(0,badaW+1):
lastValue = lastValue + stats.binom.pmf(k, badaW, p)
nextvalue =lastValue+ stats.binom.pmf(k+1, badaW, p)
print(lastValue)
print(nextvalue)
print("------------")
j =j+1
# def computeRange():
# badaW=10
# lastValue = 0;
# p = 0.5
# x = 0.0023
# j = 0
# if (x<=stats.binom.pmf(0, badaW, p)):
# j = 0
# else :
# for k in range(0,badaW+1):
# lastValue = lastValue + stats.binom.pmf(k, badaW, p)
# nextvalue =lastValue+ stats.binom.pmf(k+1, badaW, p)
# print(lastValue)
# print(nextvalue)
# print("------------")
# j =j+1
#
......@@ -187,6 +189,26 @@ def testSortition():
print(proof)
print(j)
def tester():
sk,pk = genratePublicPrivateKey()
seed = ("a",1,2)
roleCount = 26
role = "LEAD"
# w= randint(1,100000,10)
w = [ 1, 10,100, 500, 1000,5000, 8000, 10000 ]
w.sort()
print(w)
# w = 20
badaW = np.sum(w)
print(badaW)
for i in w:
hash,proof,j = sortition(sk,seed,roleCount,role,i,badaW,pk)
# print(hash) #this is a real content of hash it should be used as final thing and not hexlify
# print(binascii.hexlify(hash))
# print(proof)
print("w = " + str(i) , "w/badaW = ", str(i/badaW), "j = " ,str(j))
def testVerifySort():
sk, pk = genratePublicPrivateKey()
seed = ("a", 1, 2)
......@@ -221,6 +243,29 @@ def testVerifySort():
print(y)
assert (y==0),"Test Verify sort failed : change of seed not detected"
def tester():
'''
tests if sortition distributes the stake
:return:
'''
sk,pk = genratePublicPrivateKey()
seed = ("a",1,2)
roleCount = 26
role = "LEAD"
# w= randint(1,100000,10)
w = [ 1, 10,100, 500, 1000,5000, 8000, 10000 ]
w.sort()
print(w)
# w = 20
badaW = np.sum(w)
print(badaW)
for i in w:
hash,proof,j = sortition(sk,seed,roleCount,role,i,badaW,pk)
# print(hash) #this is a real content of hash it should be used as final thing and not hexlify
# print(binascii.hexlify(hash))
# print(proof)
print("w = " + str(i) , "w/badaW = ", str(i/badaW), "j = " ,str(j))
def testVerifyVRF():
sk,pk = genratePublicPrivateKey()
......@@ -234,4 +279,5 @@ def testVerifyVRF():
if __name__ == '__main__':
# testSortition()
# testVerifyVRF()
testVerifySort()
# testVerifySort(0
tester()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment