Skip to content

Commit

Permalink
Improve stability (#25)
Browse files Browse the repository at this point in the history
* chore: increase log level

* feat: secure relays endpoint

* feat: add config for the extension

* chore: update `min_lnbits_version`

* chore: improve logging

* fix: decrypt logic

* chore: improve logs
  • Loading branch information
motorina0 authored Jan 22, 2024
1 parent 16ae9d1 commit a119c38
Show file tree
Hide file tree
Showing 8 changed files with 220 additions and 193 deletions.
4 changes: 2 additions & 2 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
"name": "Nostr Client",
"short_description": "Nostr client for extensions",
"tile": "/nostrclient/static/images/nostr-bitcoin.png",
"contributors": ["calle"],
"min_lnbits_version": "0.11.0"
"contributors": ["calle", "motorina0"],
"min_lnbits_version": "0.12.0"
}
40 changes: 38 additions & 2 deletions crud.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from typing import List
from typing import List, Optional

import json

from . import db
from .models import Relay
from .models import Config, Relay


async def get_relays() -> List[Relay]:
Expand All @@ -25,3 +27,37 @@ async def add_relay(relay: Relay) -> None:

async def delete_relay(relay: Relay) -> None:
await db.execute("DELETE FROM nostrclient.relays WHERE url = ?", (relay.url,))


######################CONFIG#######################
async def create_config() -> Config:
config = Config()
await db.execute(
"""
INSERT INTO nostrclient.config (json_data)
VALUES (?)
""",
(json.dumps(config.dict())),
)
row = await db.fetchone(
"SELECT json_data FROM nostrclient.config", ()
)
return json.loads(row[0], object_hook=lambda d: Config(**d))


async def update_config(config: Config) -> Optional[Config]:
await db.execute(
"""UPDATE nostrclient.config SET json_data = ?""",
(json.dumps(config.dict())),
)
row = await db.fetchone(
"SELECT json_data FROM nostrclient.config", ()
)
return json.loads(row[0], object_hook=lambda d: Config(**d))


async def get_config() -> Optional[Config]:
row = await db.fetchone(
"SELECT json_data FROM nostrclient.config", ()
)
return json.loads(row[0], object_hook=lambda d: Config(**d)) if row else None
12 changes: 12 additions & 0 deletions migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,15 @@ async def m001_initial(db):
);
"""
)


async def m002_create_config_table(db):
"""
Allow the extension to persist and retrieve any number of config values.
"""

await db.execute(
"""CREATE TABLE nostrclient.config (
json_data TEXT NOT NULL
);"""
)
5 changes: 5 additions & 0 deletions models.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,8 @@ class TestMessageResponse(BaseModel):
private_key: str
public_key: str
event_json: str


class Config(BaseModel):
private_ws: bool = True
public_ws: bool = False
1 change: 1 addition & 0 deletions nostr/relay_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ def add_subscription(self, id: str, filters: List[str]):

def close_subscription(self, id: str):
try:
logger.info(f"Closing subscription: '{id}'.")
with self._subscriptions_lock:
if id in self._cached_subscriptions:
self._cached_subscriptions.pop(id)
Expand Down
8 changes: 5 additions & 3 deletions router.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ async def stop(self):
pass

try:
await self.websocket.close()
await self.websocket.close(reason="Websocket connection closed")
except Exception as _:
pass

Expand Down Expand Up @@ -113,7 +113,7 @@ async def _handle_received_subscription_events(self, s):
def _handle_notices(self):
while len(NostrRouter.received_subscription_notices):
my_event = NostrRouter.received_subscription_notices.pop(0)
logger.info(f"[Relay '{my_event.url}'] Notice: '{my_event.content}']")
logger.debug(f"[Relay '{my_event.url}'] Notice: '{my_event.content}']")
# Note: we don't send it to the user because
# we don't know who should receive it
nostr_client.relay_manager.handle_notice(my_event)
Expand All @@ -136,6 +136,7 @@ async def _handle_client_to_nostr(self, json_str):

def _handle_client_req(self, json_data):
subscription_id = json_data[1]
logger.info(f"New subscription: '{subscription_id}'")
subscription_id_rewritten = urlsafe_short_hash()
self.original_subscription_ids[subscription_id_rewritten] = subscription_id
filters = json_data[2:]
Expand All @@ -154,5 +155,6 @@ def _handle_client_close(self, subscription_id):
if subscription_id_rewritten:
self.original_subscription_ids.pop(subscription_id_rewritten)
nostr_client.relay_manager.close_subscription(subscription_id_rewritten)
logger.info(f"Unsubscribe from '{subscription_id_rewritten}'. Original id: '{subscription_id}.'")
else:
logger.debug(f"Failed to unsubscribe from '{subscription_id}.'")
logger.info(f"Failed to unsubscribe from '{subscription_id}.'")
Loading

0 comments on commit a119c38

Please sign in to comment.