Skip to content
Snippets Groups Projects
Commit 6c58ff5e authored by Johannes Hitzinger's avatar Johannes Hitzinger
Browse files

tested sign function of line

parent b19e6a96
No related branches found
No related tags found
No related merge requests found
......@@ -22,12 +22,13 @@ from util import get_pub_ip
logger = logging.getLogger(__name__)
# TODO: is Connection (cable or transformer) involved in confirming trades? can this be be prevented?
class Connection:
def __init__(self, cap: float, conips: set[ipaddress.IPv4Address], sched: AsyncIOScheduler):
self.dil = Dilithium(dilithium.dilithium.DEFAULT_PARAMETERS["dilithium3"])
self.__secretKey, self.publicKey = self.dil.keygen(
self.publicKey, self.secretKey = self.dil.keygen(
[randint(0, numpy.iinfo('uint32').max), randint(0, numpy.iinfo('uint32').max),
randint(0, numpy.iinfo('uint32').max), randint(0, numpy.iinfo('uint32').max)])
self.fastRouter = APIRouter()
......@@ -37,3 +38,9 @@ class Connection:
self.availableCapacity = cap
self.usedCapacity = 0
self.loss = 0.01 # this is a wrong assumption, actual line loss is depending on the load
def checkCapacity(self, rc: RemoteConnection):
if self.availableCapacity - self.usedCapacity > rc.tradeCapacity:
self.usedCapacity += rc.tradeCapacity + rc.loss
return True
return False
......@@ -50,25 +50,30 @@ class Line(Connection):
return jsonpickle.encode(rl)
async def sign(self, time: datetime.datetime, rljson):
print(rljson)
rl = jsonpickle.decode(rljson)
if rl.publicKey == self.publicKey: # check if the rl actually is me
time = time.replace(second=0, microsecond=0) # we are scheduling in minute intervals
if time not in self.lastSignedLine.keys():
origin = SignedRemoteLine(
RemoteLine(self.publicIP, self.publicKey, self.availableCapacity,
self.usedCapacity, self.adjacentConnections, self.loss), None)
origin.isOrigin = True
origin.signature = self.dil.sign_with_input(self.__secretKey, origin.__str__())
result = SignedRemoteLine(rl, origin)
result.signature = self.dil.sign_with_input(self.__secretKey, result.__str__())
self.lastSignedLine[time] = result
return jsonpickle.encode(result)
else:
# if there has been a route announced before, add the previous to the new one
result = SignedRemoteLine(rl, self.lastSignedLine[time])
result.signature = self.dil.sign_with_input(self.__secretKey, result.__str__())
self.lastSignedLine[time] = result
return jsonpickle.encode(result)
if self.checkCapacity(rl):
print(self.secretKey)
time = time.replace(second=0, microsecond=0) # we are scheduling in minute intervals
if time not in self.lastSignedLine.keys():
origin = SignedRemoteLine(
RemoteLine(self.publicIP, self.publicKey, self.availableCapacity,
self.usedCapacity, self.adjacentConnections, self.loss), None)
origin.isOrigin = True
origin.signature = self.dil.sign_with_input(self.secretKey, origin.__str__().encode())
result = SignedRemoteLine(rl, origin)
result.signature = self.dil.sign_with_input(self.secretKey, result.__str__().encode())
self.lastSignedLine[time] = result
return jsonpickle.encode(result)
else:
# if there has been a route announced before, add the previous to the new one
result = SignedRemoteLine(rl, self.lastSignedLine[time])
result.signature = self.dil.sign_with_input(self.secretKey, result.__str__().encode())
self.lastSignedLine[time] = result
return jsonpickle.encode(result)
else: # TODO: Rest Error handling
return "Not enough capacity" # better handling here would be nice
else:
return "Unauthorized" # better handling here would be nice
......
import asyncio
import dataclasses
import datetime
import ipaddress
import sys
import random
......@@ -24,6 +25,7 @@ from pint import UnitRegistry
import settings
import participant
import line
import DHTdummy
import rustworkx as rx
......@@ -60,6 +62,7 @@ class CustomDijkstraVisitor(DijkstraVisitor):
def discover_vertex(self, vertex, distance):
print(f"Discovered vertex: {vertex} with distance: {distance}")
def examine_edge(self, edge):
for e in self.examined_edges:
if edge[0] == e[1] and edge[1] == e[0]:
......@@ -145,7 +148,7 @@ e1 = p1 * t1
#e1.ito(ureg.kilowatt_hour)
print(e1)
'''
'''
d1 = Dilithium(dilithium.dilithium.DEFAULT_PARAMETERS["dilithium3"])
pk, sk = d1.keygen([random.randint(0, numpy.iinfo('uint32').max), random.randint(0, numpy.iinfo('uint32').max),
random.randint(0, numpy.iinfo('uint32').max),
......@@ -153,8 +156,9 @@ pk, sk = d1.keygen([random.randint(0, numpy.iinfo('uint32').max), random.randint
msg = b"this is a message"
sig = d1.sign_with_input(sk, msg)
result = d1.verify(pk, msg, sig)
#print(result)
'''
print(sk)
print(result)
jobstores = {
'default': MemoryJobStore()
}
......@@ -175,19 +179,23 @@ async def lifespan(app: FastAPI):
scheduler.shutdown()
# fast_app = FastAPI(lifespan=lifespan)
fast_app = FastAPI(lifespan=lifespan)
# start the server
'''
if __name__ == "__main__":
@scheduler.scheduled_job('interval', seconds=100)
def scheduled_job_1():
logger.info("hello from " + get_ip())
print(datetime.datetime.now())
part = participant.Participant(nid="test_network", dht_ep={ipaddress.IPv4Address(
'172.20.0.2')}, con_ip=ipaddress.IPv4Address('172.20.1.1')) # Network_ID should be a Hash for real world use, provide ip adresses of dht endpoints for first discovery
l = line.Line(cap=100, conips={ipaddress.IPv4Address('0.0.0.0')}, sched=scheduler)
rl = asyncio.run(l.asRemoteLineJSON())
print(rl)
#part = participant.Participant(nid="test_network", dht_ep={ipaddress.IPv4Address(
# '172.20.0.2')}, con_ip=ipaddress.IPv4Address('172.20.1.1')) # Network_ID should be a Hash for real world use, provide ip adresses of dht endpoints for first discovery
#scheduler.add_job(part.requestremoteParticipants, 'interval', seconds=20, id='1', name='requestRemoteParticipants')
fast_app.include_router(part.fastRouter)
fast_app.include_router(l.fastRouter)
uvicorn.run(fast_app, host=get_ip(), port=8000)
'''
......@@ -335,16 +335,19 @@ class Participant:
self.trade: Trade = trade
def discover_vertex(self, vertex, distance):
logger.info(f"Discovered Trafo: {vertex}")
with httpx.Client as client:
response = client.post("http://" + self.trade.route.graph[vertex].publicIP.__str__() + ":8000/sign/"
+ self.trade.offer.executiontime.__str__() + "?rljson=" + jsonpickle.encode(
self.trade.route.graph[vertex]))
logger.info(f"===> Discovered Trafo: {self.trade.route.graph[vertex].publicIP}")
def examine_edge(self, edge):
for e in self.examined_edges:
if edge[0] == e[1] and edge[1] == e[0]:
logger.info(f"Line already examined: {edge}")
logger.info(f"===>Line already examined: {edge[2].publicIP}")
return
logger.info(f"Examining Line: {edge}")
logger.info(f"===>Examining Line: {edge[2].publicIP}")
self.examined_edges.add(edge)
visitor = GridVisitor(t)
......@@ -379,7 +382,6 @@ class Participant:
# now announce the route to all connections involved
await self.announceRoute(t)
logger.info("===> found offer on " + closest.publicIP.__str__())
else:
logger.info("===> no one to trade with on " + self.publicIP.__str__())
......
......@@ -8,6 +8,7 @@ class RemoteConnection:
self.publicKey: bytes = pk
self.availableCapacity: float = cap
self.usedCapacity: float = ucap
self.tradeCapacity: float = 0
self.loss = l # loss rate during transmission or transformation
self.timestamp = time.time_ns()
......
......@@ -14,8 +14,8 @@ class Trade:
self.ureg = None
self.Q_ = None
self.__timestamp = time.time_ns()
self.__offer: offer.Offer = off
self.__request: request.Request = req
self.offer: offer.Offer = off
self.request: request.Request = req
self.route = rou
self.power = pwr
self.__pricePerWatt = ppw
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment