From d6fa754a6d744582189237eb47d78f7f53ac7691 Mon Sep 17 00:00:00 2001 From: callebtc <93376500+callebtc@users.noreply.github.com> Date: Sat, 29 Oct 2022 22:55:32 +0200 Subject: [PATCH] test tor --- cashu/tor/tor.py | 21 +++++++++++---------- cashu/wallet/wallet.py | 4 +--- tests/test_tor.py | 19 +++++++++++++++++++ 3 files changed, 31 insertions(+), 13 deletions(-) create mode 100644 tests/test_tor.py diff --git a/cashu/tor/tor.py b/cashu/tor/tor.py index 766fcf2..c41ca02 100755 --- a/cashu/tor/tor.py +++ b/cashu/tor/tor.py @@ -9,10 +9,10 @@ from loguru import logger class TorProxy: - def __init__(self): + def __init__(self, keep_alive=False): self.base_path = pathlib.Path(__file__).parent.resolve() self.platform = platform.system() - self.keep_alive = 60 * 60 # seconds + self.keep_alive = 60 * 60 if keep_alive else 0 # seconds self.tor_proc = None self.pid_file = os.path.join(self.base_path, "tor.pid") self.tor_pid = None @@ -32,14 +32,15 @@ class TorProxy: self.run_daemon() def run_daemon(self): + cmd = [ + f"{self.tor_path()}", + "--defaults-torrc", + f"{self.tor_config_path()}", + ] + if self.keep_alive and platform.system() != "Windows": + cmd = ["timeout", f"{self.keep_alive}"] + cmd self.tor_proc = subprocess.Popen( - [ - "timeout", - "20", - f"{self.tor_path()}", - "--defaults-torrc", - f"{self.tor_config_path()}", - ], + cmd, shell=False, close_fds=True, stdout=subprocess.PIPE, @@ -68,7 +69,7 @@ class TorProxy: # make sure that file has correct permissions try: logger.debug(f"Setting permissions of {PATHS[platform.system()]} to 755") - os.chmod(PATHS[platform.system()], 755) + os.chmod(PATHS[platform.system()], 0o755) except: raise Exception("error setting permissions for tor binary.") return PATHS[platform.system()] diff --git a/cashu/wallet/wallet.py b/cashu/wallet/wallet.py index 6b360f3..9cf1d2e 100644 --- a/cashu/wallet/wallet.py +++ b/cashu/wallet/wallet.py @@ -64,8 +64,7 @@ class LedgerAPI: def _set_requests(self): s = requests.Session() if TOR: - # overwrite custom settings - tor = TorProxy() + tor = TorProxy(keep_alive=True) tor.wait_until_startup() socks_host, socks_port = "localhost", 9050 else: @@ -78,7 +77,6 @@ class LedgerAPI: } s.proxies.update(proxies) s.headers.update({"User-Agent": scrts.token_urlsafe(8)}) - print(s.get(self.url + "/keys").json()) return s diff --git a/tests/test_tor.py b/tests/test_tor.py new file mode 100644 index 0000000..3965a7e --- /dev/null +++ b/tests/test_tor.py @@ -0,0 +1,19 @@ +import requests +from cashu.tor.tor import TorProxy + + +def test_tor_setup(): + s = requests.Session() + + tor = TorProxy(keep_alive=False) + tor.wait_until_startup() + socks_host, socks_port = "localhost", 9050 + + proxies = { + "http": f"socks5://{socks_host}:{socks_port}", + "https": f"socks5://{socks_host}:{socks_port}", + } + s.proxies.update(proxies) + + resp = s.get("https://google.com") + resp.raise_for_status()