Skip to content

acync #1

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

Open
wants to merge 3 commits into
base: development
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
18 changes: 12 additions & 6 deletions application/app/application.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,42 @@
import asyncio
import platform
from abc import ABC


from application.app.setup.console_setup import ConsoleSetup
from application.app.setup.logger_setup import LoggerSetup
from application.app.setup.p2p_setup import P2PNodeSetup
from application.app.setup.tor_setup import TorSetup
from application.logger.logger import Logger
from application.settings import APP_NAME
from application.settings import PROXY_HOST
from application.settings import PROXY_PORT
from application.settings import NODE_HOST
from application.settings import NODE_PORT
from application.version import APP_VERSION
from application.p2p.node import Node
from application.app.de_app import DeApp


class DeProtocol(ABC):

def __init__(self):
self.setups = {}
self.on_start()

def on_start(self, proxy_host='127.0.0.1', proxy_port=9050):
async def on_start(self, proxy_host: str = PROXY_HOST, proxy_port: int = PROXY_PORT) -> None:
self.setups = {
'logger': LoggerSetup(),
'tor': TorSetup(proxy_host, proxy_port),
'p2p': P2PNodeSetup(NODE_HOST, NODE_PORT),
'shell': ConsoleSetup()
}

for setup in self.setups.values():
setup.setup()

ConsoleSetup(self.setups['p2p'].node, self.setups['tor'].tor_service).setup()
await setup.setup()

app = DeApp(self.setups['p2p'].node, self.setups['tor'].tor_service, self.setups['shell'].shell)
Logger.get_instance().info(f"Starting {APP_NAME} version {APP_VERSION}, running on {platform.system()}")
await app.start()

def on_stop(self):
def on_stop(self) -> None:
pass
15 changes: 15 additions & 0 deletions application/app/de_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# from application.console.simple_console import DeConsole
from application.network.tor_network import TorService
from application.p2p.node import Node


class DeApp:
def __init__(self, node: Node, tor_service: TorService, shell):
self.node = node
self.tor_service = tor_service
self.shell = shell

async def start(self) -> None:
init_shell_vars = [self, self.tor_service, self.node]
await self.shell.start(*init_shell_vars)

12 changes: 4 additions & 8 deletions application/app/setup/console_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,10 @@

class ConsoleSetup(SetupABC):

def __init__(self, node, tor_service):
self.shell = None
self.node = node
self.tor_service = tor_service
def __init__(self):
self.shell: DeConsole = None

def setup(self):
async def setup(self):
if USE_CONSOLE:
Logger.get_instance().warning("Running DeProtocol in CONSOLE MODE!")
self.shell = DeConsole(self.node, self.tor_service)
self.shell.start()
Logger.get_instance().info("Console started correctly!")
self.shell = DeConsole()
7 changes: 3 additions & 4 deletions application/app/setup/logger_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,15 @@

from application.app.setup.setup import SetupABC
from application.logger.logger import Logger
from application.settings import APP_NAME, PROXY_HOST, PROXY_PORT, PROXY_TYPE, NODE_HOST, NODE_PORT, DEBUG, \
DEFAULT_LOG_LEVEL
from application.settings import APP_NAME, DEFAULT_LOG_LEVEL


class LoggerSetup(SetupABC):

def __init__(self):
self.logger = None
self.logger: Logger = None

def setup(self):
async def setup(self) -> None:
log_level = DEFAULT_LOG_LEVEL

self.logger = Logger(name=APP_NAME, level=log_level)
Expand Down
7 changes: 3 additions & 4 deletions application/app/setup/p2p_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@


class P2PNodeSetup(SetupABC):
def __init__(self, node_host, node_port):
def __init__(self, node_host: str, node_port: int):
self.node = None
self.node_host = node_host
self.node_port = node_port

def setup(self):
# Start Node
async def setup(self) -> None:
self.node = Node(self.node_host, self.node_port)
self.node.start()
await self.node.start()
Logger.get_instance().info(f"Node started correctly! Host:Port -> {self.node_host}:{self.node_port}")
2 changes: 1 addition & 1 deletion application/app/setup/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@

class SetupABC(ABC):
@abstractmethod
def setup(self):
def setup(self) -> None:
pass
15 changes: 10 additions & 5 deletions application/app/setup/tor_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,32 @@
from application.logger.logger import Logger
from application.network.tor_network import TorService
from application.settings import PROXY_TYPE
from application.settings import PROXY_PORT
from application.settings import PROXY_HOST
from application.settings import CONTROL_PORT
from application.utils.tor_utils import TorUtils



class TorSetup(SetupABC):
def __init__(self, proxy_host='127.0.0.1', proxy_port=9050):
def __init__(self, proxy_host: str = PROXY_HOST, proxy_port: int = PROXY_PORT):
self.tor_service = None
self.tor_client = None
self.proxy_host = proxy_host
self.proxy_port = proxy_port

def setup(self):
async def setup(self) -> None:
# Configure socks to use Tor proxy by default
socks.setdefaultproxy(PROXY_TYPE, self.proxy_host, self.proxy_port)

Logger.get_instance().info(
f'Default proxy configuration set: {PROXY_TYPE} - {self.proxy_host}:{self.proxy_port}')

# Download and install Tor Client
self.tor_client = TorUtils()
self.tor_client.download_and_install()
await self.tor_client.install()

# Start Tor Service
self.tor_service = TorService(9051)
self.tor_service.start()
self.tor_service = TorService(CONTROL_PORT)
await self.tor_service.start()
Logger.get_instance().info("Tor Service started correctly!")
58 changes: 40 additions & 18 deletions application/console/simple_console.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,57 @@
import threading
import asyncio
import time

from application.logger.logger import Logger
from application.app.de_app import DeApp
from application.settings import NODE_PORT


class DeConsole(threading.Thread):
class DeConsole:
def __init__(self):
self.app = None
self.tor_service = None
self.node = None
self.terminate_flag = asyncio.Event()

def __init__(self, node, tor_service):
super().__init__()
self.node = node
self.tor_service = tor_service
self.terminate_flag = threading.Event()
async def start(self, *args, **kwargs) -> None:

def set_cls_vars() -> None:
if args:
self.app, self.tor_service, self.node = args
Logger.get_instance().info("Console started correctly!")

try:
set_cls_vars()
except Exception as exs:
Logger.get_instance().error(exs)

def run(self):
while not self.terminate_flag.is_set():
try:
self.handle_console()

await self.handle_console()

except KeyboardInterrupt:
Logger.get_instance().info("User requested stopping the protocol, stopping!")
self.stop()

# BUG: add exception for bug "Invalid protocol version"

except Exception as exc:
Logger.get_instance().info(f"An exception is stopping DeProtocol! ({exc})")
self.stop()

Logger.get_instance().info("DeProtocol successfully closed, see you soon!")

def stop(self):
def stop(self) -> None:
self.terminate_flag.set()

def handle_console(self):
cmd = input("\nDEPROTO>")
async def handle_console(self) -> None:

async def async_input(prompt='') -> str:
print(prompt, end='', flush=True)
return (await asyncio.get_running_loop().run_in_executor(None, input)).rstrip('\n')

cmd = await async_input("\nDEPROTO>")
if cmd == "help":
print(
"""
Expand All @@ -42,12 +65,12 @@ def handle_console(self):
)
if "connect " in cmd:
args = cmd.replace("connect ", "")
self.node.connect(args, port=65432)
await self.node.connect(args, port=65432)

if "msg " in cmd:
args = cmd.replace("msg ", "")
Logger.get_instance().info(f"Sent message: {args}")
self.node.message("msg", args)
await self.node.message("msg", args)

if cmd == "stop":
self.node.stop()
Expand All @@ -69,11 +92,10 @@ def handle_console(self):
if cmd == "peers":
self.print_peers()

def print_peers(self):
def print_peers(self) -> None:
print(f"Address: {self.tor_service.get_address()}")
Logger.get_instance().info(self.node.peers)
print("--------------")
for i in self.node.nodes_connected:
for i in self.node.node_connections:
print(
i.id
+ " ("
Expand All @@ -82,6 +104,6 @@ def print_peers(self):
+ str(time.time() - int(i.last_ping))
+ "s"
)
if len(self.node.peers) == 0:
if len(self.node.node_connections) == 0:
print("NO PEERS CONNECTED")
print("--------------")
12 changes: 6 additions & 6 deletions application/logger/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class Logger:
""" Represents a Logger object handles logging functionalities executed as a singleton"""
_instance = None

def __init__(self, name, level=logging.INFO, fmt='[%(asctime)s] %(levelname)s: %(message)s',
def __init__(self, name: str, level=logging.INFO, fmt='[%(asctime)s] %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'):
self.logger = logging.getLogger(name)
self.logger.setLevel(level)
Expand All @@ -28,22 +28,22 @@ def __init__(self, name, level=logging.INFO, fmt='[%(asctime)s] %(levelname)s: %

#stem_logger.addHandler(logging.StreamHandler())

def level(self, level="trace"):
def level(self, level="trace") -> None:
self.logger.setLevel(level)

def info(self, msg, *args, **kwargs):
def info(self, msg: str, *args, **kwargs) -> None:
""" Information prints in logging terms """
self.logger.info(msg, *args, **kwargs)

def warning(self, msg, *args, **kwargs):
def warning(self, msg: str, *args, **kwargs) -> None:
""" Warning prints in logging terms """
self.logger.warning(msg, *args, **kwargs)

def error(self, msg, *args, **kwargs):
def error(self, msg: str, *args, **kwargs) -> None:
""" Error prints in logging terms"""
self.logger.error(msg, *args, **kwargs)

def debug(self, msg, *args, **kwargs):
def debug(self, msg: str, *args, **kwargs) -> None:
""" Debug prints in logging terms """
self.logger.debug(msg, *args, **kwargs)

Expand Down
Loading