Compare commits
12 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
801ce44561 | ||
|
|
507003ac20 |
||
|
|
5a078f2bfc |
||
|
|
d0f1089f08 |
||
|
|
571b034004 |
||
|
|
c871a42a85 |
||
|
|
e66f997853 |
||
|
|
02af516903 |
||
|
|
89f7c99f75 |
||
|
|
bd355a8a01 |
||
|
|
ed67ad3294 |
||
|
|
c42735ca85 |
19 changed files with 2542 additions and 2804 deletions
9
.github/workflows/ci.yml
vendored
9
.github/workflows/ci.yml
vendored
|
|
@ -11,14 +11,9 @@ jobs:
|
|||
tests:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [lint]
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: ['3.9', '3.10']
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: lnbits/lnbits/.github/actions/prepare@dev
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
- name: Run pytest
|
||||
uses: pavelzw/pytest-action@v2
|
||||
env:
|
||||
|
|
@ -30,5 +25,5 @@ jobs:
|
|||
job-summary: true
|
||||
emoji: false
|
||||
click-to-expand: true
|
||||
custom-pytest: poetry run pytest
|
||||
report-title: 'test (${{ matrix.python-version }})'
|
||||
custom-pytest: uv run pytest
|
||||
report-title: 'test'
|
||||
|
|
|
|||
24
Makefile
24
Makefile
|
|
@ -5,27 +5,27 @@ format: prettier black ruff
|
|||
check: mypy pyright checkblack checkruff checkprettier
|
||||
|
||||
prettier:
|
||||
poetry run ./node_modules/.bin/prettier --write .
|
||||
uv run ./node_modules/.bin/prettier --write .
|
||||
pyright:
|
||||
poetry run ./node_modules/.bin/pyright
|
||||
uv run ./node_modules/.bin/pyright
|
||||
|
||||
mypy:
|
||||
poetry run mypy .
|
||||
uv run mypy .
|
||||
|
||||
black:
|
||||
poetry run black .
|
||||
uv run black .
|
||||
|
||||
ruff:
|
||||
poetry run ruff check . --fix
|
||||
uv run ruff check . --fix
|
||||
|
||||
checkruff:
|
||||
poetry run ruff check .
|
||||
uv run ruff check .
|
||||
|
||||
checkprettier:
|
||||
poetry run ./node_modules/.bin/prettier --check .
|
||||
uv run ./node_modules/.bin/prettier --check .
|
||||
|
||||
checkblack:
|
||||
poetry run black --check .
|
||||
uv run black --check .
|
||||
|
||||
checkeditorconfig:
|
||||
editorconfig-checker
|
||||
|
|
@ -33,14 +33,14 @@ checkeditorconfig:
|
|||
test:
|
||||
PYTHONUNBUFFERED=1 \
|
||||
DEBUG=true \
|
||||
poetry run pytest
|
||||
uv run pytest
|
||||
install-pre-commit-hook:
|
||||
@echo "Installing pre-commit hook to git"
|
||||
@echo "Uninstall the hook with poetry run pre-commit uninstall"
|
||||
poetry run pre-commit install
|
||||
@echo "Uninstall the hook with uv run pre-commit uninstall"
|
||||
uv run pre-commit install
|
||||
|
||||
pre-commit:
|
||||
poetry run pre-commit run --all-files
|
||||
uv run pre-commit run --all-files
|
||||
|
||||
|
||||
checkbundle:
|
||||
|
|
|
|||
119
README.md
119
README.md
|
|
@ -2,14 +2,123 @@
|
|||
|
||||
<small>For more about LNBits extension check [this tutorial](https://github.com/lnbits/lnbits/wiki/LNbits-Extensions)</small>
|
||||
|
||||
`nostrclient` is an always-on extension that can open multiple connections to nostr relays and act as a multiplexer for other clients: You open a single websocket to `nostrclient` which then sends the data to multiple relays. The responses from these relays are then sent back to the client.
|
||||
## Overview
|
||||
|
||||

|
||||
`nostrclient` is an always-on Nostr relay multiplexer that simplifies connecting to multiple Nostr relays. Instead of your Nostr client managing connections to dozens of relays, you connect to a single WebSocket endpoint provided by `nostrclient`, which then fans out your requests to all configured relays and aggregates the responses back to you.
|
||||
|
||||
### Troubleshoot
|
||||
### Why Use This?
|
||||
|
||||
The `Test Endpoint` functionality heps the user to check that the `nostrclient` web-socket endpoint works as expected.
|
||||
- **Simplified Client Configuration** - Connect to one endpoint instead of managing multiple relay connections
|
||||
- **Always-On Connectivity** - Your LNbits instance maintains persistent connections to relays
|
||||
- **Resource Efficient** - Share relay connections across multiple clients
|
||||
- **Subscription Management** - Automatic subscription ID rewriting prevents conflicts between clients
|
||||
|
||||
The LNbits user can DM itself (or a temp account) from `nostrclient` and verify that the messages are sent and received correctly.
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[Client A] -->|WebSocket| N
|
||||
B[Client B] -->|WebSocket| N
|
||||
C[Client C] -->|WebSocket| N
|
||||
|
||||
N[nostrclient<br/>Router] -->|Fan Out| R1[Relay A]
|
||||
N -->|Fan Out| R2[Relay B]
|
||||
N -->|Fan Out| R3[Relay C]
|
||||
N -->|Fan Out| R4[Relay D]
|
||||
|
||||
R1 -.->|Aggregate| N
|
||||
R2 -.->|Aggregate| N
|
||||
R3 -.->|Aggregate| N
|
||||
R4 -.->|Aggregate| N
|
||||
```
|
||||
|
||||
**Key Feature:** The router rewrites subscription IDs to prevent conflicts when multiple clients use the same IDs.
|
||||
|
||||
## Features
|
||||
|
||||
- **Multi-Relay Multiplexing** - Connect to multiple Nostr relays through a single WebSocket
|
||||
- **Public & Private Endpoints** - Configurable public and private WebSocket access
|
||||
- **Automatic Reconnection** - Failed relays are automatically retried with exponential backoff
|
||||
- **Subscription Deduplication** - Events are deduplicated before being sent to clients
|
||||
- **Health Monitoring** - Track relay connection status, latency, and error rates
|
||||
- **Test Endpoint** - Send test messages to verify your setup is working
|
||||
|
||||
## How It Works
|
||||
|
||||
1. **Client Connection** - Your Nostr client connects to the nostrclient WebSocket endpoint
|
||||
2. **Subscription Rewriting** - Each subscription ID is rewritten to prevent conflicts between multiple clients
|
||||
3. **Fan-Out** - Subscription requests are sent to all configured relays
|
||||
4. **Aggregation** - Events from all relays are collected and deduplicated
|
||||
5. **Response** - Events are sent back to the client with the original subscription ID
|
||||
|
||||
## Configuration
|
||||
|
||||
### WebSocket Endpoints
|
||||
|
||||
- **Public Endpoint**: `/api/v1/relay` - Available to anyone (if enabled)
|
||||
- **Private Endpoint**: `/api/v1/{encrypted_id}` - Requires valid encrypted endpoint ID
|
||||
|
||||
Configure endpoint access in the extension settings:
|
||||
|
||||
- `private_ws` - Enable/disable private WebSocket access
|
||||
- `public_ws` - Enable/disable public WebSocket access
|
||||
|
||||
### Adding Relays
|
||||
|
||||
Use the nostrclient UI to add/remove Nostr relays. The extension will automatically:
|
||||
|
||||
- Connect to new relays
|
||||
- Publish existing subscriptions to new relays
|
||||
- Monitor relay health and reconnect as needed
|
||||
|
||||
## Testing
|
||||
|
||||
### Test Endpoint Functionality
|
||||
|
||||
The `Test Endpoint` feature helps verify that your nostrclient WebSocket endpoint works correctly.
|
||||
|
||||
**How to test:**
|
||||
|
||||
1. Navigate to the nostrclient extension in LNbits
|
||||
2. Use the Test Endpoint feature
|
||||
3. Send a DM to yourself (or a temporary account)
|
||||
4. Verify that messages are sent and received correctly
|
||||
|
||||
https://user-images.githubusercontent.com/2951406/236780745-929c33c2-2502-49be-84a3-db02a7aabc0e.mp4
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Connection Issues
|
||||
|
||||
- **Check relay status** - View relay health in the nostrclient UI
|
||||
- **Verify endpoint configuration** - Ensure public_ws or private_ws is enabled
|
||||
- **Check logs** - Review LNbits logs for connection errors
|
||||
|
||||
### Subscription Not Receiving Events
|
||||
|
||||
- **Verify relays are connected** - Check the relay status in the UI
|
||||
- **Test with known event** - Use the Test Endpoint to verify connectivity
|
||||
- **Check relay compatibility** - Some relays may not support all Nostr features
|
||||
|
||||
## Development
|
||||
|
||||
This extension uses `uv` for dependency management.
|
||||
|
||||
### Quick Start
|
||||
|
||||
```bash
|
||||
# Format code
|
||||
make format
|
||||
|
||||
# Run type checks and linting
|
||||
make check
|
||||
|
||||
# Run tests
|
||||
make test
|
||||
```
|
||||
|
||||
For more development commands, see the [Makefile](./Makefile).
|
||||
|
||||
## License
|
||||
|
||||
MIT License - see [LICENSE](./LICENSE)
|
||||
|
|
|
|||
|
|
@ -53,7 +53,7 @@ def nostrclient_start():
|
|||
__all__ = [
|
||||
"db",
|
||||
"nostrclient_ext",
|
||||
"nostrclient_start",
|
||||
"nostrclient_static_files",
|
||||
"nostrclient_stop",
|
||||
"nostrclient_start",
|
||||
]
|
||||
|
|
|
|||
14
config.json
14
config.json
|
|
@ -1,7 +1,17 @@
|
|||
{
|
||||
"name": "Nostr Client",
|
||||
"short_description": "Nostr client for extensions",
|
||||
"short_description": "Nostr relay multiplexer",
|
||||
"version": "1.1.0",
|
||||
"tile": "/nostrclient/static/images/nostr-bitcoin.png",
|
||||
"contributors": ["calle", "motorina0", "dni"],
|
||||
"min_lnbits_version": "1.0.0"
|
||||
"min_lnbits_version": "1.4.0",
|
||||
"images": [
|
||||
{
|
||||
"uri": "https://raw.githubusercontent.com/lnbits/nostrclient/add-extension-metadata/static/images/1.jpeg"
|
||||
},
|
||||
{
|
||||
"uri": "https://raw.githubusercontent.com/lnbits/nostrclient/add-extension-metadata/static/images/2.jpeg"
|
||||
}
|
||||
],
|
||||
"description_md": "https://raw.githubusercontent.com/lnbits/nostrclient/add-extension-metadata/description.md"
|
||||
}
|
||||
|
|
|
|||
4
crud.py
4
crud.py
|
|
@ -1,5 +1,3 @@
|
|||
from typing import Optional
|
||||
|
||||
from lnbits.db import Database
|
||||
|
||||
from .models import Config, Relay, UserConfig
|
||||
|
|
@ -40,7 +38,7 @@ async def update_config(owner_id: str, config: Config) -> Config:
|
|||
return user_config.extra
|
||||
|
||||
|
||||
async def get_config(owner_id: str) -> Optional[Config]:
|
||||
async def get_config(owner_id: str) -> Config | None:
|
||||
user_config: UserConfig = await db.fetchone(
|
||||
"""
|
||||
SELECT * FROM nostrclient.config
|
||||
|
|
|
|||
|
|
@ -1 +1,8 @@
|
|||
An always-on extension that can open multiple connections to nostr relays and act as a multiplexer for other clients: You open a single websocket to nostrclient which then sends the data to multiple relays. The responses from these relays are then sent back to the client.
|
||||
An always-on relay multiplexer that simplifies connecting to multiple Nostr relays.
|
||||
|
||||
Instead of your Nostr client managing connections to dozens of relays, you connect to a single WebSocket endpoint provided by `nostrclient`, which then fans out your requests to all configured relays and aggregates the responses back to you.
|
||||
|
||||
- **Simplified Client Configuration** - Connect to one endpoint instead of managing multiple relay connections
|
||||
- **Always-On Connectivity** - Your LNbits instance maintains persistent connections to relays
|
||||
- **Resource Efficient** - Share relay connections across multiple clients
|
||||
- **Automatic Subscription Management** - Subscription ID rewriting prevents conflicts between clients
|
||||
|
|
|
|||
30
models.py
30
models.py
|
|
@ -1,27 +1,25 @@
|
|||
from typing import Optional
|
||||
|
||||
from lnbits.helpers import urlsafe_short_hash
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class RelayStatus(BaseModel):
|
||||
num_sent_events: Optional[int] = 0
|
||||
num_received_events: Optional[int] = 0
|
||||
error_counter: Optional[int] = 0
|
||||
error_list: Optional[list] = []
|
||||
notice_list: Optional[list] = []
|
||||
num_sent_events: int | None = 0
|
||||
num_received_events: int | None = 0
|
||||
error_counter: int | None = 0
|
||||
error_list: list | None = []
|
||||
notice_list: list | None = []
|
||||
|
||||
|
||||
class Relay(BaseModel):
|
||||
id: Optional[str] = None
|
||||
url: Optional[str] = None
|
||||
active: Optional[bool] = None
|
||||
id: str | None = None
|
||||
url: str | None = None
|
||||
active: bool | None = None
|
||||
|
||||
connected: Optional[bool] = Field(default=None, no_database=True)
|
||||
connected_string: Optional[str] = Field(default=None, no_database=True)
|
||||
status: Optional[RelayStatus] = Field(default=None, no_database=True)
|
||||
connected: bool | None = Field(default=None, no_database=True)
|
||||
connected_string: str | None = Field(default=None, no_database=True)
|
||||
status: RelayStatus | None = Field(default=None, no_database=True)
|
||||
|
||||
ping: Optional[int] = Field(default=None, no_database=True)
|
||||
ping: int | None = Field(default=None, no_database=True)
|
||||
|
||||
def _init__(self):
|
||||
if not self.id:
|
||||
|
|
@ -31,11 +29,11 @@ class Relay(BaseModel):
|
|||
class RelayDb(BaseModel):
|
||||
id: str
|
||||
url: str
|
||||
active: Optional[bool] = True
|
||||
active: bool | None = True
|
||||
|
||||
|
||||
class TestMessage(BaseModel):
|
||||
sender_private_key: Optional[str]
|
||||
sender_private_key: str | None
|
||||
reciever_public_key: str
|
||||
message: str
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ from enum import IntEnum
|
|||
from hashlib import sha256
|
||||
from typing import Optional
|
||||
|
||||
from secp256k1 import PublicKey
|
||||
import coincurve
|
||||
|
||||
from .message_type import ClientMessageType
|
||||
|
||||
|
|
@ -75,12 +75,8 @@ class Event:
|
|||
def verify(self) -> bool:
|
||||
assert self.public_key
|
||||
assert self.signature
|
||||
pub_key = PublicKey(
|
||||
bytes.fromhex("02" + self.public_key), True
|
||||
) # add 02 for schnorr (bip340)
|
||||
return pub_key.schnorr_verify(
|
||||
bytes.fromhex(self.id), bytes.fromhex(self.signature), None, raw=True
|
||||
)
|
||||
pub_key = coincurve.PublicKeyXOnly(bytes.fromhex(self.public_key))
|
||||
return pub_key.verify(bytes.fromhex(self.signature), bytes.fromhex(self.id))
|
||||
|
||||
def to_message(self) -> str:
|
||||
return json.dumps(
|
||||
|
|
|
|||
50
nostr/key.py
50
nostr/key.py
|
|
@ -1,9 +1,7 @@
|
|||
import base64
|
||||
import secrets
|
||||
from typing import Optional
|
||||
|
||||
import secp256k1
|
||||
from cffi import FFI
|
||||
import coincurve
|
||||
from cryptography.hazmat.primitives import padding
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
|
||||
|
|
@ -23,15 +21,13 @@ class PublicKey:
|
|||
return self.raw_bytes.hex()
|
||||
|
||||
def verify_signed_message_hash(self, message_hash: str, sig: str) -> bool:
|
||||
pk = secp256k1.PublicKey(b"\x02" + self.raw_bytes, True)
|
||||
return pk.schnorr_verify(
|
||||
bytes.fromhex(message_hash), bytes.fromhex(sig), None, True
|
||||
)
|
||||
pk = coincurve.PublicKeyXOnly(self.raw_bytes)
|
||||
return pk.verify(bytes.fromhex(sig), bytes.fromhex(message_hash))
|
||||
|
||||
@classmethod
|
||||
def from_npub(cls, npub: str):
|
||||
"""Load a PublicKey from its bech32/npub form"""
|
||||
hrp, data, spec = bech32_decode(npub)
|
||||
_, data, _ = bech32_decode(npub)
|
||||
raw_data = convertbits(data, 5, 8)
|
||||
assert raw_data
|
||||
raw_public_key = raw_data[:-1]
|
||||
|
|
@ -39,20 +35,20 @@ class PublicKey:
|
|||
|
||||
|
||||
class PrivateKey:
|
||||
def __init__(self, raw_secret: Optional[bytes] = None) -> None:
|
||||
def __init__(self, raw_secret: bytes | None = None) -> None:
|
||||
if raw_secret is not None:
|
||||
self.raw_secret = raw_secret
|
||||
else:
|
||||
self.raw_secret = secrets.token_bytes(32)
|
||||
|
||||
sk = secp256k1.PrivateKey(self.raw_secret)
|
||||
assert sk.pubkey
|
||||
self.public_key = PublicKey(sk.pubkey.serialize()[1:])
|
||||
sk = coincurve.PrivateKey(self.raw_secret)
|
||||
assert sk.public_key
|
||||
self.public_key = PublicKey(sk.public_key.format()[1:])
|
||||
|
||||
@classmethod
|
||||
def from_nsec(cls, nsec: str):
|
||||
"""Load a PrivateKey from its bech32/nsec form"""
|
||||
hrp, data, spec = bech32_decode(nsec)
|
||||
_, data, _ = bech32_decode(nsec)
|
||||
raw_data = convertbits(data, 5, 8)
|
||||
assert raw_data
|
||||
raw_secret = raw_data[:-1]
|
||||
|
|
@ -66,12 +62,13 @@ class PrivateKey:
|
|||
return self.raw_secret.hex()
|
||||
|
||||
def tweak_add(self, scalar: bytes) -> bytes:
|
||||
sk = secp256k1.PrivateKey(self.raw_secret)
|
||||
return sk.tweak_add(scalar)
|
||||
sk = coincurve.PrivateKey(self.raw_secret)
|
||||
return sk.add(scalar).to_der()
|
||||
|
||||
def compute_shared_secret(self, public_key_hex: str) -> bytes:
|
||||
pk = secp256k1.PublicKey(bytes.fromhex("02" + public_key_hex), True)
|
||||
return pk.ecdh(self.raw_secret, hashfn=copy_x)
|
||||
pk = coincurve.PublicKey(bytes.fromhex("02" + public_key_hex))
|
||||
sk = coincurve.PrivateKey(self.raw_secret)
|
||||
return sk.ecdh(pk.format())
|
||||
|
||||
def encrypt_message(self, message: str, public_key_hex: str) -> str:
|
||||
padder = padding.PKCS7(128).padder()
|
||||
|
|
@ -116,8 +113,8 @@ class PrivateKey:
|
|||
return unpadded_data.decode()
|
||||
|
||||
def sign_message_hash(self, message_hash: bytes) -> str:
|
||||
sk = secp256k1.PrivateKey(self.raw_secret)
|
||||
sig = sk.schnorr_sign(message_hash, None, raw=True)
|
||||
sk = coincurve.PrivateKey(self.raw_secret)
|
||||
sig = sk.sign_schnorr(message_hash)
|
||||
return sig.hex()
|
||||
|
||||
def sign_event(self, event: Event) -> None:
|
||||
|
|
@ -131,9 +128,7 @@ class PrivateKey:
|
|||
return self.raw_secret == other.raw_secret
|
||||
|
||||
|
||||
def mine_vanity_key(
|
||||
prefix: Optional[str] = None, suffix: Optional[str] = None
|
||||
) -> PrivateKey:
|
||||
def mine_vanity_key(prefix: str | None = None, suffix: str | None = None) -> PrivateKey:
|
||||
if prefix is None and suffix is None:
|
||||
raise ValueError("Expected at least one of 'prefix' or 'suffix' arguments")
|
||||
|
||||
|
|
@ -149,14 +144,3 @@ def mine_vanity_key(
|
|||
break
|
||||
|
||||
return sk
|
||||
|
||||
|
||||
ffi = FFI()
|
||||
|
||||
|
||||
@ffi.callback(
|
||||
"int (unsigned char *, const unsigned char *, const unsigned char *, void *)"
|
||||
)
|
||||
def copy_x(output, x32, y32, data):
|
||||
ffi.memmove(output, x32, 32)
|
||||
return 1
|
||||
|
|
|
|||
2655
poetry.lock
generated
2655
poetry.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -1,47 +1,44 @@
|
|||
[tool.poetry]
|
||||
[project]
|
||||
name = "lnbits-nostrclient"
|
||||
version = "0.0.0"
|
||||
version = "1.1.0"
|
||||
requires-python = ">=3.10,<3.13"
|
||||
description = "LNbits, free and open-source Lightning wallet and accounts system."
|
||||
authors = ["Alan Bits <alan@lnbits.com>"]
|
||||
authors = [{ name = "Alan Bits", email = "alan@lnbits.com" }]
|
||||
urls = { Homepage = "https://lnbits.com", Repository = "https://github.com/lnbits/nostrclient" }
|
||||
dependencies = [ "lnbits>1" ]
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = "^3.10 | ^3.9"
|
||||
lnbits = {allow-prereleases = true, version = "*"}
|
||||
[tool.poetry]
|
||||
package-mode = false
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
black = "^24.3.0"
|
||||
pytest-asyncio = "^0.21.0"
|
||||
pytest = "^7.3.2"
|
||||
mypy = "^1.5.1"
|
||||
pre-commit = "^3.2.2"
|
||||
ruff = "^0.3.2"
|
||||
types-cffi = "^1.16.0.20240331"
|
||||
pytest-md = "^0.2.0"
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core>=1.0.0"]
|
||||
build-backend = "poetry.core.masonry.api"
|
||||
[tool.uv]
|
||||
dev-dependencies = [
|
||||
"black",
|
||||
"pytest-asyncio",
|
||||
"pytest",
|
||||
"mypy",
|
||||
"pre-commit",
|
||||
"ruff",
|
||||
"pytest-md",
|
||||
"types-cffi",
|
||||
]
|
||||
|
||||
[tool.mypy]
|
||||
exclude = "(nostr/*)"
|
||||
plugins = ["pydantic.mypy"]
|
||||
|
||||
[[tool.mypy.overrides]]
|
||||
module = [
|
||||
"nostr.*",
|
||||
"lnbits.*",
|
||||
"lnurl.*",
|
||||
"loguru.*",
|
||||
"fastapi.*",
|
||||
"pydantic.*",
|
||||
"pyqrcode.*",
|
||||
"shortuuid.*",
|
||||
"httpx.*",
|
||||
"secp256k1.*",
|
||||
"websocket.*",
|
||||
]
|
||||
follow_imports = "skip"
|
||||
ignore_missing_imports = "True"
|
||||
|
||||
[tool.pydantic-mypy]
|
||||
init_forbid_extra = true
|
||||
init_typed = true
|
||||
warn_required_dynamic_aliases = true
|
||||
warn_untyped_fields = true
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
log_cli = false
|
||||
testpaths = [
|
||||
|
|
|
|||
18
router.py
18
router.py
|
|
@ -1,6 +1,6 @@
|
|||
import asyncio
|
||||
import json
|
||||
from typing import ClassVar, Dict, List
|
||||
from typing import ClassVar
|
||||
|
||||
from fastapi import WebSocket, WebSocketDisconnect
|
||||
from lnbits.helpers import urlsafe_short_hash
|
||||
|
|
@ -16,7 +16,7 @@ all_routers: list["NostrRouter"] = []
|
|||
|
||||
|
||||
class NostrRouter:
|
||||
received_subscription_events: ClassVar[dict[str, List[EventMessage]]] = {}
|
||||
received_subscription_events: ClassVar[dict[str, list[EventMessage]]] = {}
|
||||
received_subscription_notices: ClassVar[list[NoticeMessage]] = []
|
||||
received_subscription_eosenotices: ClassVar[dict[str, EndOfStoredEventsMessage]] = (
|
||||
{}
|
||||
|
|
@ -25,11 +25,11 @@ class NostrRouter:
|
|||
def __init__(self, websocket: WebSocket):
|
||||
self.connected: bool = True
|
||||
self.websocket: WebSocket = websocket
|
||||
self.tasks: List[asyncio.Task] = []
|
||||
self.original_subscription_ids: Dict[str, str] = {}
|
||||
self.tasks: list[asyncio.Task] = []
|
||||
self.original_subscription_ids: dict[str, str] = {}
|
||||
|
||||
@property
|
||||
def subscriptions(self) -> List[str]:
|
||||
def subscriptions(self) -> list[str]:
|
||||
return list(self.original_subscription_ids.keys())
|
||||
|
||||
def start(self):
|
||||
|
|
@ -111,10 +111,14 @@ class NostrRouter:
|
|||
# this reconstructs the original response from the relay
|
||||
# reconstruct original subscription id
|
||||
s_original = self.original_subscription_ids[s]
|
||||
event_to_forward = f"""["EVENT", "{s_original}", {event_json}]"""
|
||||
event_to_forward = json.dumps(
|
||||
["EVENT", s_original, json.loads(event_json)]
|
||||
)
|
||||
await self.websocket.send_text(event_to_forward)
|
||||
except Exception as e:
|
||||
logger.debug(e) # there are 2900 errors here
|
||||
logger.warning(
|
||||
f"[NOSTRCLIENT] Error in _handle_received_subscription_events: {e}"
|
||||
)
|
||||
|
||||
def _handle_notices(self):
|
||||
while len(NostrRouter.received_subscription_notices):
|
||||
|
|
|
|||
BIN
static/images/1.jpeg
Normal file
BIN
static/images/1.jpeg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 488 KiB |
BIN
static/images/2.jpeg
Normal file
BIN
static/images/2.jpeg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 300 KiB |
|
|
@ -466,8 +466,7 @@
|
|||
predefinedRelays: [
|
||||
'wss://relay.damus.io',
|
||||
'wss://nostr-pub.wellorder.net',
|
||||
'wss://nostr.zebedee.cloud',
|
||||
'wss://nodestr.fmt.wiz.biz',
|
||||
'wss://relay.nostrconnect.com',
|
||||
'wss://nostr.oxtr.dev',
|
||||
'wss://nostr.wine'
|
||||
]
|
||||
|
|
@ -477,11 +476,7 @@
|
|||
getRelays: function () {
|
||||
var self = this
|
||||
LNbits.api
|
||||
.request(
|
||||
'GET',
|
||||
'/nostrclient/api/v1/relays?usr=' + this.g.user.id,
|
||||
this.g.user.wallets[0].adminkey
|
||||
)
|
||||
.request('GET', '/nostrclient/api/v1/relays')
|
||||
.then(function (response) {
|
||||
if (response.data) {
|
||||
response.data.map(maplrelays)
|
||||
|
|
@ -509,12 +504,9 @@
|
|||
console.log('ADD RELAY ' + this.relayToAdd)
|
||||
let that = this
|
||||
LNbits.api
|
||||
.request(
|
||||
'POST',
|
||||
'/nostrclient/api/v1/relay?usr=' + this.g.user.id,
|
||||
this.g.user.wallets[0].adminkey,
|
||||
{url: this.relayToAdd}
|
||||
)
|
||||
.request('POST', '/nostrclient/api/v1/relay', null, {
|
||||
url: this.relayToAdd
|
||||
})
|
||||
.then(function (response) {
|
||||
console.log('response:', response)
|
||||
if (response.data) {
|
||||
|
|
@ -541,12 +533,7 @@
|
|||
},
|
||||
deleteRelay(url) {
|
||||
LNbits.api
|
||||
.request(
|
||||
'DELETE',
|
||||
'/nostrclient/api/v1/relay?usr=' + this.g.user.id,
|
||||
this.g.user.wallets[0].adminkey,
|
||||
{url: url}
|
||||
)
|
||||
.request('DELETE', '/nostrclient/api/v1/relay', null, {url: url})
|
||||
.then(response => {
|
||||
const relayIndex = this.nostrrelayLinks.indexOf(r => r.url === url)
|
||||
if (relayIndex !== -1) {
|
||||
|
|
@ -562,8 +549,7 @@
|
|||
try {
|
||||
const {data} = await LNbits.api.request(
|
||||
'GET',
|
||||
'/nostrclient/api/v1/config',
|
||||
this.g.user.wallets[0].adminkey
|
||||
'/nostrclient/api/v1/config'
|
||||
)
|
||||
this.config.data = data
|
||||
} catch (error) {
|
||||
|
|
@ -575,7 +561,7 @@
|
|||
const {data} = await LNbits.api.request(
|
||||
'PUT',
|
||||
'/nostrclient/api/v1/config',
|
||||
this.g.user.wallets[0].adminkey,
|
||||
null,
|
||||
this.config.data
|
||||
)
|
||||
this.config.data = data
|
||||
|
|
@ -624,7 +610,7 @@
|
|||
const {data} = await LNbits.api.request(
|
||||
'PUT',
|
||||
'/nostrclient/api/v1/relay/test',
|
||||
this.g.user.wallets[0].adminkey,
|
||||
null,
|
||||
{
|
||||
sender_private_key: this.testData.senderPrivateKey,
|
||||
reciever_public_key: this.testData.recieverPublicKey,
|
||||
|
|
|
|||
8
views.py
8
views.py
|
|
@ -1,6 +1,7 @@
|
|||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
from lnbits.core.models import User
|
||||
from lnbits.core.crud.users import get_user_from_account
|
||||
from lnbits.core.models.users import Account
|
||||
from lnbits.decorators import check_admin
|
||||
from lnbits.helpers import template_renderer
|
||||
|
||||
|
|
@ -12,7 +13,10 @@ def nostr_renderer():
|
|||
|
||||
|
||||
@nostrclient_generic_router.get("/", response_class=HTMLResponse)
|
||||
async def index(request: Request, user: User = Depends(check_admin)):
|
||||
async def index(request: Request, account: Account = Depends(check_admin)):
|
||||
user = await get_user_from_account(account)
|
||||
if not user:
|
||||
return HTMLResponse("No user found", status_code=404)
|
||||
return nostr_renderer().TemplateResponse(
|
||||
"nostrclient/index.html", {"request": request, "user": user.json()}
|
||||
)
|
||||
|
|
|
|||
|
|
@ -131,7 +131,7 @@ async def ws_relay(ws_id: str, websocket: WebSocket) -> None:
|
|||
else:
|
||||
if not config.private_ws:
|
||||
raise ValueError("Private websocket connections not accepted.")
|
||||
if decrypt_internal_message(ws_id) != "relay":
|
||||
if decrypt_internal_message(ws_id, urlsafe=True) != "relay":
|
||||
raise ValueError("Invalid websocket endpoint.")
|
||||
|
||||
await websocket.accept()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue