Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lilione #9

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ services:
build:
context: .
dockerfile: Dockerfile
ports:
- "4000:4000"
- "4001:4001"
- "4002:4002"
- "4003:4003"
- "8545:8545"
volumes:
- ./ratel:/usr/src/hbswap/ratel
- ./MP-SPDZ/compile.py:/usr/src/hbswap/compile.py
Expand Down
124 changes: 41 additions & 83 deletions front-end/webpage.html

Large diffs are not rendered by default.

471 changes: 161 additions & 310 deletions front-end/webpage.js

Large diffs are not rendered by default.

33 changes: 32 additions & 1 deletion ratel/src/python/Server.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
import re

from aiohttp import web
from ratel.src.python.utils import key_inputmask
from ratel.src.python.utils import key_inputmask, key_balance, get_value, hex_to_int, key_individual_price


class Server:
def __init__(self, serverID, db, host, http_port):
Expand All @@ -25,6 +26,30 @@ async def handler_inputmask(request):
print(f"s{self.serverID} response: {res}")
return web.json_response(data)

async def handler_balance(request):
print(f"s{self.serverID} request: {request}")
user, token = re.split(",", request.match_info.get("user_token"))
res = int.from_bytes(bytes(get_value(self.db, key_balance(user.lower(), token))), 'big')
data = {
"balance": f"{res}"
}
print(f"s{self.serverID} response: {res}")
return web.json_response(data)

async def handler_price(request):
print(f"s{self.serverID} request: {request}")
trade_seq = request.match_info.get("trade_seq")
res = ''
try:
res = int.from_bytes(bytes(self.db.Get(key_individual_price(trade_seq))), 'big')
except KeyError:
pass
data = {
"price": f"{res}"
}
print(f"s{self.serverID} response: {res}")
return web.json_response(data)

app = web.Application()

cors = aiohttp_cors.setup(app, defaults={
Expand All @@ -38,6 +63,12 @@ async def handler_inputmask(request):
resource = cors.add(app.router.add_resource("/inputmasks/{mask_idxes}"))
cors.add(resource.add_route("GET", handler_inputmask))

resource = cors.add(app.router.add_resource("/balance/{user_token}"))
cors.add(resource.add_route("GET", handler_balance))

resource = cors.add(app.router.add_resource("/price/{trade_seq}"))
cors.add(resource.add_route("GET", handler_price))

runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, host=self.host, port=self.http_port)
Expand Down
2 changes: 1 addition & 1 deletion ratel/src/python/badgerswapv3/addLiquidity.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,4 @@ def addLiquidity(appContract, token0, token1, priceLower, priceUpper, maxAmtA, m
appContract = web3.eth.contract(address=appAddress, abi=abi)

account = getAccount(web3, f"/opt/poa/keystore/server_0/")
addLiquidity(appContract, ETH, tokenAddress, 1, 2, 10, 10)
addLiquidity(appContract, ETH, tokenAddress, 1, 2, 10, 10)
2 changes: 0 additions & 2 deletions ratel/src/python/badgerswapv3/deposit.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ def approve(tokenContract, receiver, amt):
tx_hash = tokenContract.functions.approve(receiver, int(amt * fp)).transact()
web3.eth.wait_for_transaction_receipt(tx_hash)


def deposit(appContract, token, amt, tokenContract):
if token == ETH:
tx_hash = appContract.functions.publicDeposit(token, int(amt * fp)).transact(
Expand All @@ -24,7 +23,6 @@ def deposit(appContract, token, amt, tokenContract):
tx_hash = appContract.functions.secretDeposit(token, int(amt * fp)).transact()
web3.eth.wait_for_transaction_receipt(tx_hash)


if __name__ == "__main__":
web3 = Web3(Web3.WebsocketProvider(url))

Expand Down
1 change: 0 additions & 1 deletion ratel/src/python/badgerswapv3/trade.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
)
from ratel.src.python.utils import fp, blsPrime


def trade(appContract, tokenA, tokenB, amtA, amtB):
amtA = int(amtA * fp)
amtB = int(amtB * fp)
Expand Down
228 changes: 114 additions & 114 deletions ratel/src/python/httpserver.py
Original file line number Diff line number Diff line change
@@ -1,124 +1,124 @@
import sys

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
#
from .config import settings
# from ..utils import (
# key_balance,
# key_inputmask,
# key_individual_price,
# location_db,
# openDB,
# get_value,
# hex_to_int
# import sys
#
# from fastapi import FastAPI, HTTPException
# from fastapi.middleware.cors import CORSMiddleware
# #
# # from .config import settings
# # from ..utils import (
# # key_balance,
# # key_inputmask,
# # key_individual_price,
# # location_db,
# # openDB,
# # get_value,
# # hex_to_int
# # )
# from ratel.src.python.utils import openDB, location_db, key_inputmask, hex_to_int, key_balance, get_value
#
# app = FastAPI()
#
# app.add_middleware(
# CORSMiddleware,
# allow_origins="*",
# allow_credentials=True,
# allow_methods=["*"],
# allow_headers=["*"],
# )
from ratel.src.python.utils import openDB, location_db, key_inputmask

app = FastAPI()

app.add_middleware(
CORSMiddleware,
allow_origins="*",
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)


@app.get("/")
async def root():
return {"message": "Hello HoneyBadgerSwap!"}


@app.get("/info")
async def info():
return {"info": "hbswap http server"}


@app.get("/inputmasks/{mask_idxes}")
async def get_inputmasks(mask_idxes: str):
print(f"s{serverID} processing request GET /inputmasks/{mask_idxes}")
mask_idx_list = mask_idxes.split(",")
res = ""
print(mask_idx_list)
db = openDB(location_db(serverID))
for mask_idx in mask_idx_list:
try:
share = int.from_bytes(bytes(db.Get(key_inputmask(mask_idx))), 'big')
except KeyError:
print('key error: ', mask_idx)
res = ''
break
res += (
f"{',' if len(res) > 0 else ''}{share}"
)
data = {"inputmask_shares": res}
print(f"s{serverID} response to GET /inputmasks/{mask_idxes}: {res}")
return data


# @app.get("/price/{trade_seq}")
# async def get_price(trade_seq: str):
# print(f"s{settings.NODE_ID} processing request GET /price/{trade_seq}")
# db = openDB(location_db(settings.NODE_ID))
# res = ''
# try:
# res = hex_to_int(bytes(db.Get(key_individual_price(trade_seq))))
# except KeyError:
# pass
# data = {"price": f"{res}"}
# print(f"s{settings.NODE_ID} response to GET /price/{trade_seq}: {res}")
#
#
# @app.get("/")
# async def root():
# return {"message": "Hello HoneyBadgerSwap!"}
#
#
# @app.get("/info")
# async def info():
# return {"info": "hbswap http server"}
#
#
# @app.get("/inputmasks/{mask_idxes}")
# async def get_inputmasks(mask_idxes: str):
# print(f"s{serverID} processing request GET /inputmasks/{mask_idxes}")
# mask_idx_list = mask_idxes.split(",")
# res = ""
# print(mask_idx_list)
# db = openDB(location_db(serverID))
# for mask_idx in mask_idx_list:
# try:
# share = int.from_bytes(bytes(db.Get(key_inputmask(mask_idx))), 'big')
# except KeyError:
# print('key error: ', mask_idx)
# res = ''
# break
# res += (
# f"{',' if len(res) > 0 else ''}{share}"
# )
# data = {"inputmask_shares": res}
# print(f"s{serverID} response to GET /inputmasks/{mask_idxes}: {res}")
# return data
#
#
# # @app.get("/price/{trade_seq}")
# # async def get_price(trade_seq: str):
# # print(f"s{settings.NODE_ID} processing request GET /price/{trade_seq}")
# # db = openDB(location_db(settings.NODE_ID))
# # res = ''
# # try:
# # res = hex_to_int(bytes(db.Get(key_individual_price(trade_seq))))
# # except KeyError:
# # pass
# # data = {"price": f"{res}"}
# # print(f"s{settings.NODE_ID} response to GET /price/{trade_seq}: {res}")
# # return data
# #
# #
# @app.get("/balance/{token_user}")
# async def get_balance(token_user: str):
# print(f"s{settings.NODE_ID} processing request GET /balance/{token_user}")
# token, user = token_user.split(",")
# db = openDB(location_db(settings.NODE_ID))
# async def get_balance(user_token: str):
# print(f"s{serverID} processing request GET /balance/{user_token}")
# token, user = user_token.split(",")
# db = openDB(location_db(serverID))
# res = hex_to_int(get_value(db, key_balance(token, user)))
# data = {"balance": f"{res}"}
# print(f"s{settings.NODE_ID} response to GET /balance/{token_user}: {res}")
# print(f"s{serverID} response to GET /balance/{user_token}: {res}")
# return data
# #
# #
# # @app.get("/log/{n}")
# # async def get_logs(n: int):
# # print(f"s{settings.NODE_ID} processing request GET /log/{n}")
# # log_file = open(f"/usr/src/hbswap/log/mpc_server_{settings.NODE_ID}.log", "r")
# # lines = log_file.readlines()
# # last_lines = lines[-n:]
# # res = ""
# # for line in last_lines:
# # res += line
# # data = {"log": f"{res}"}
# # print(f"s{settings.NODE_ID} response to GET /log/{n}: {res}")
# # return data
#
#
# @app.get("/log/{n}")
# async def get_logs(n: int):
# print(f"s{settings.NODE_ID} processing request GET /log/{n}")
# log_file = open(f"/usr/src/hbswap/log/mpc_server_{settings.NODE_ID}.log", "r")
# lines = log_file.readlines()
# last_lines = lines[-n:]
# res = ""
# for line in last_lines:
# res += line
# data = {"log": f"{res}"}
# print(f"s{settings.NODE_ID} response to GET /log/{n}: {res}")
# return data


def start_server():
# import argparse
import uvicorn

# parser = argparse.ArgumentParser("Start HoneyBadgerSwap HTTP server.")
# parser.add_argument(
# "--log-level",
# type=str,
# choices=("critical", "error", "warning", "info", "debug", "trace"),
# default="info",
# help="set log level",
# )
# args = parser.parse_args()

uvicorn.run(
"ratel.src.python.httpserver:app",
host="0.0.0.0",
port=4000 + serverID,
)


if __name__ == "__main__":
serverID = int(sys.argv[1])

start_server()
# def start_server():
# # import argparse
# import uvicorn
#
# # parser = argparse.ArgumentParser("Start HoneyBadgerSwap HTTP server.")
# # parser.add_argument(
# # "--log-level",
# # type=str,
# # choices=("critical", "error", "warning", "info", "debug", "trace"),
# # default="info",
# # help="set log level",
# # )
# # args = parser.parse_args()
#
# uvicorn.run(
# "ratel.src.python.httpserver:app",
# host="0.0.0.0",
# port=4000 + serverID,
# )
#
#
# if __name__ == "__main__":
# serverID = int(sys.argv[1])
#
# start_server()
17 changes: 17 additions & 0 deletions ratel/src/python/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@
def mpcPort():
return 5000

def key_balance(user, token):
print('key', f'balance_{user}_{token}')
return f'balance_{user}_{token}'.encode()

def key_individual_price(trade_seq):
print('**** server', f'tradePrice_{trade_seq}')
return f'tradePrice_{trade_seq}'.encode()

def key_inputmask(idx):
return f'inputmask_{idx}'.encode()

Expand Down Expand Up @@ -46,6 +54,9 @@ def get_inverse(a):
a = (a * a) % blsPrime
return ret

def fix_to_float(x):
return 1. * x / fp

def recover_input(db, masked_value, idx): # return: int
try:
input_mask_share = db.Get(key_inputmask(idx))
Expand All @@ -54,6 +65,12 @@ def recover_input(db, masked_value, idx): # return: int
input_mask_share = int.from_bytes(input_mask_share, 'big')
return (masked_value - input_mask_share) % blsPrime

def get_value(db, key): # return: hex
try:
return bytes(db.Get(key))
except KeyError:
return int_to_hex(0)

prog = './malicious-shamir-party.x'
players = 4
threshold = 1
Expand Down
Loading