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:
|
tests:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs: [lint]
|
needs: [lint]
|
||||||
strategy:
|
|
||||||
matrix:
|
|
||||||
python-version: ['3.9', '3.10']
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: lnbits/lnbits/.github/actions/prepare@dev
|
- uses: lnbits/lnbits/.github/actions/prepare@dev
|
||||||
with:
|
|
||||||
python-version: ${{ matrix.python-version }}
|
|
||||||
- name: Run pytest
|
- name: Run pytest
|
||||||
uses: pavelzw/pytest-action@v2
|
uses: pavelzw/pytest-action@v2
|
||||||
env:
|
env:
|
||||||
|
|
@ -30,5 +25,5 @@ jobs:
|
||||||
job-summary: true
|
job-summary: true
|
||||||
emoji: false
|
emoji: false
|
||||||
click-to-expand: true
|
click-to-expand: true
|
||||||
custom-pytest: poetry run pytest
|
custom-pytest: uv run pytest
|
||||||
report-title: 'test (${{ matrix.python-version }})'
|
report-title: 'test'
|
||||||
|
|
|
||||||
24
Makefile
24
Makefile
|
|
@ -5,27 +5,27 @@ format: prettier black ruff
|
||||||
check: mypy pyright checkblack checkruff checkprettier
|
check: mypy pyright checkblack checkruff checkprettier
|
||||||
|
|
||||||
prettier:
|
prettier:
|
||||||
poetry run ./node_modules/.bin/prettier --write .
|
uv run ./node_modules/.bin/prettier --write .
|
||||||
pyright:
|
pyright:
|
||||||
poetry run ./node_modules/.bin/pyright
|
uv run ./node_modules/.bin/pyright
|
||||||
|
|
||||||
mypy:
|
mypy:
|
||||||
poetry run mypy .
|
uv run mypy .
|
||||||
|
|
||||||
black:
|
black:
|
||||||
poetry run black .
|
uv run black .
|
||||||
|
|
||||||
ruff:
|
ruff:
|
||||||
poetry run ruff check . --fix
|
uv run ruff check . --fix
|
||||||
|
|
||||||
checkruff:
|
checkruff:
|
||||||
poetry run ruff check .
|
uv run ruff check .
|
||||||
|
|
||||||
checkprettier:
|
checkprettier:
|
||||||
poetry run ./node_modules/.bin/prettier --check .
|
uv run ./node_modules/.bin/prettier --check .
|
||||||
|
|
||||||
checkblack:
|
checkblack:
|
||||||
poetry run black --check .
|
uv run black --check .
|
||||||
|
|
||||||
checkeditorconfig:
|
checkeditorconfig:
|
||||||
editorconfig-checker
|
editorconfig-checker
|
||||||
|
|
@ -33,14 +33,14 @@ checkeditorconfig:
|
||||||
test:
|
test:
|
||||||
PYTHONUNBUFFERED=1 \
|
PYTHONUNBUFFERED=1 \
|
||||||
DEBUG=true \
|
DEBUG=true \
|
||||||
poetry run pytest
|
uv run pytest
|
||||||
install-pre-commit-hook:
|
install-pre-commit-hook:
|
||||||
@echo "Installing pre-commit hook to git"
|
@echo "Installing pre-commit hook to git"
|
||||||
@echo "Uninstall the hook with poetry run pre-commit uninstall"
|
@echo "Uninstall the hook with uv run pre-commit uninstall"
|
||||||
poetry run pre-commit install
|
uv run pre-commit install
|
||||||
|
|
||||||
pre-commit:
|
pre-commit:
|
||||||
poetry run pre-commit run --all-files
|
uv run pre-commit run --all-files
|
||||||
|
|
||||||
|
|
||||||
checkbundle:
|
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>
|
<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
|
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__ = [
|
__all__ = [
|
||||||
"db",
|
"db",
|
||||||
"nostrclient_ext",
|
"nostrclient_ext",
|
||||||
|
"nostrclient_start",
|
||||||
"nostrclient_static_files",
|
"nostrclient_static_files",
|
||||||
"nostrclient_stop",
|
"nostrclient_stop",
|
||||||
"nostrclient_start",
|
|
||||||
]
|
]
|
||||||
|
|
|
||||||
14
config.json
14
config.json
|
|
@ -1,7 +1,17 @@
|
||||||
{
|
{
|
||||||
"name": "Nostr Client",
|
"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",
|
"tile": "/nostrclient/static/images/nostr-bitcoin.png",
|
||||||
"contributors": ["calle", "motorina0", "dni"],
|
"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 lnbits.db import Database
|
||||||
|
|
||||||
from .models import Config, Relay, UserConfig
|
from .models import Config, Relay, UserConfig
|
||||||
|
|
@ -40,7 +38,7 @@ async def update_config(owner_id: str, config: Config) -> Config:
|
||||||
return user_config.extra
|
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(
|
user_config: UserConfig = await db.fetchone(
|
||||||
"""
|
"""
|
||||||
SELECT * FROM nostrclient.config
|
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 lnbits.helpers import urlsafe_short_hash
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
class RelayStatus(BaseModel):
|
class RelayStatus(BaseModel):
|
||||||
num_sent_events: Optional[int] = 0
|
num_sent_events: int | None = 0
|
||||||
num_received_events: Optional[int] = 0
|
num_received_events: int | None = 0
|
||||||
error_counter: Optional[int] = 0
|
error_counter: int | None = 0
|
||||||
error_list: Optional[list] = []
|
error_list: list | None = []
|
||||||
notice_list: Optional[list] = []
|
notice_list: list | None = []
|
||||||
|
|
||||||
|
|
||||||
class Relay(BaseModel):
|
class Relay(BaseModel):
|
||||||
id: Optional[str] = None
|
id: str | None = None
|
||||||
url: Optional[str] = None
|
url: str | None = None
|
||||||
active: Optional[bool] = None
|
active: bool | None = None
|
||||||
|
|
||||||
connected: Optional[bool] = Field(default=None, no_database=True)
|
connected: bool | None = Field(default=None, no_database=True)
|
||||||
connected_string: Optional[str] = Field(default=None, no_database=True)
|
connected_string: str | None = Field(default=None, no_database=True)
|
||||||
status: Optional[RelayStatus] = 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):
|
def _init__(self):
|
||||||
if not self.id:
|
if not self.id:
|
||||||
|
|
@ -31,11 +29,11 @@ class Relay(BaseModel):
|
||||||
class RelayDb(BaseModel):
|
class RelayDb(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
url: str
|
url: str
|
||||||
active: Optional[bool] = True
|
active: bool | None = True
|
||||||
|
|
||||||
|
|
||||||
class TestMessage(BaseModel):
|
class TestMessage(BaseModel):
|
||||||
sender_private_key: Optional[str]
|
sender_private_key: str | None
|
||||||
reciever_public_key: str
|
reciever_public_key: str
|
||||||
message: str
|
message: str
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ from enum import IntEnum
|
||||||
from hashlib import sha256
|
from hashlib import sha256
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from secp256k1 import PublicKey
|
import coincurve
|
||||||
|
|
||||||
from .message_type import ClientMessageType
|
from .message_type import ClientMessageType
|
||||||
|
|
||||||
|
|
@ -75,12 +75,8 @@ class Event:
|
||||||
def verify(self) -> bool:
|
def verify(self) -> bool:
|
||||||
assert self.public_key
|
assert self.public_key
|
||||||
assert self.signature
|
assert self.signature
|
||||||
pub_key = PublicKey(
|
pub_key = coincurve.PublicKeyXOnly(bytes.fromhex(self.public_key))
|
||||||
bytes.fromhex("02" + self.public_key), True
|
return pub_key.verify(bytes.fromhex(self.signature), bytes.fromhex(self.id))
|
||||||
) # add 02 for schnorr (bip340)
|
|
||||||
return pub_key.schnorr_verify(
|
|
||||||
bytes.fromhex(self.id), bytes.fromhex(self.signature), None, raw=True
|
|
||||||
)
|
|
||||||
|
|
||||||
def to_message(self) -> str:
|
def to_message(self) -> str:
|
||||||
return json.dumps(
|
return json.dumps(
|
||||||
|
|
|
||||||
50
nostr/key.py
50
nostr/key.py
|
|
@ -1,9 +1,7 @@
|
||||||
import base64
|
import base64
|
||||||
import secrets
|
import secrets
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
import secp256k1
|
import coincurve
|
||||||
from cffi import FFI
|
|
||||||
from cryptography.hazmat.primitives import padding
|
from cryptography.hazmat.primitives import padding
|
||||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||||
|
|
||||||
|
|
@ -23,15 +21,13 @@ class PublicKey:
|
||||||
return self.raw_bytes.hex()
|
return self.raw_bytes.hex()
|
||||||
|
|
||||||
def verify_signed_message_hash(self, message_hash: str, sig: str) -> bool:
|
def verify_signed_message_hash(self, message_hash: str, sig: str) -> bool:
|
||||||
pk = secp256k1.PublicKey(b"\x02" + self.raw_bytes, True)
|
pk = coincurve.PublicKeyXOnly(self.raw_bytes)
|
||||||
return pk.schnorr_verify(
|
return pk.verify(bytes.fromhex(sig), bytes.fromhex(message_hash))
|
||||||
bytes.fromhex(message_hash), bytes.fromhex(sig), None, True
|
|
||||||
)
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_npub(cls, npub: str):
|
def from_npub(cls, npub: str):
|
||||||
"""Load a PublicKey from its bech32/npub form"""
|
"""Load a PublicKey from its bech32/npub form"""
|
||||||
hrp, data, spec = bech32_decode(npub)
|
_, data, _ = bech32_decode(npub)
|
||||||
raw_data = convertbits(data, 5, 8)
|
raw_data = convertbits(data, 5, 8)
|
||||||
assert raw_data
|
assert raw_data
|
||||||
raw_public_key = raw_data[:-1]
|
raw_public_key = raw_data[:-1]
|
||||||
|
|
@ -39,20 +35,20 @@ class PublicKey:
|
||||||
|
|
||||||
|
|
||||||
class PrivateKey:
|
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:
|
if raw_secret is not None:
|
||||||
self.raw_secret = raw_secret
|
self.raw_secret = raw_secret
|
||||||
else:
|
else:
|
||||||
self.raw_secret = secrets.token_bytes(32)
|
self.raw_secret = secrets.token_bytes(32)
|
||||||
|
|
||||||
sk = secp256k1.PrivateKey(self.raw_secret)
|
sk = coincurve.PrivateKey(self.raw_secret)
|
||||||
assert sk.pubkey
|
assert sk.public_key
|
||||||
self.public_key = PublicKey(sk.pubkey.serialize()[1:])
|
self.public_key = PublicKey(sk.public_key.format()[1:])
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_nsec(cls, nsec: str):
|
def from_nsec(cls, nsec: str):
|
||||||
"""Load a PrivateKey from its bech32/nsec form"""
|
"""Load a PrivateKey from its bech32/nsec form"""
|
||||||
hrp, data, spec = bech32_decode(nsec)
|
_, data, _ = bech32_decode(nsec)
|
||||||
raw_data = convertbits(data, 5, 8)
|
raw_data = convertbits(data, 5, 8)
|
||||||
assert raw_data
|
assert raw_data
|
||||||
raw_secret = raw_data[:-1]
|
raw_secret = raw_data[:-1]
|
||||||
|
|
@ -66,12 +62,13 @@ class PrivateKey:
|
||||||
return self.raw_secret.hex()
|
return self.raw_secret.hex()
|
||||||
|
|
||||||
def tweak_add(self, scalar: bytes) -> bytes:
|
def tweak_add(self, scalar: bytes) -> bytes:
|
||||||
sk = secp256k1.PrivateKey(self.raw_secret)
|
sk = coincurve.PrivateKey(self.raw_secret)
|
||||||
return sk.tweak_add(scalar)
|
return sk.add(scalar).to_der()
|
||||||
|
|
||||||
def compute_shared_secret(self, public_key_hex: str) -> bytes:
|
def compute_shared_secret(self, public_key_hex: str) -> bytes:
|
||||||
pk = secp256k1.PublicKey(bytes.fromhex("02" + public_key_hex), True)
|
pk = coincurve.PublicKey(bytes.fromhex("02" + public_key_hex))
|
||||||
return pk.ecdh(self.raw_secret, hashfn=copy_x)
|
sk = coincurve.PrivateKey(self.raw_secret)
|
||||||
|
return sk.ecdh(pk.format())
|
||||||
|
|
||||||
def encrypt_message(self, message: str, public_key_hex: str) -> str:
|
def encrypt_message(self, message: str, public_key_hex: str) -> str:
|
||||||
padder = padding.PKCS7(128).padder()
|
padder = padding.PKCS7(128).padder()
|
||||||
|
|
@ -116,8 +113,8 @@ class PrivateKey:
|
||||||
return unpadded_data.decode()
|
return unpadded_data.decode()
|
||||||
|
|
||||||
def sign_message_hash(self, message_hash: bytes) -> str:
|
def sign_message_hash(self, message_hash: bytes) -> str:
|
||||||
sk = secp256k1.PrivateKey(self.raw_secret)
|
sk = coincurve.PrivateKey(self.raw_secret)
|
||||||
sig = sk.schnorr_sign(message_hash, None, raw=True)
|
sig = sk.sign_schnorr(message_hash)
|
||||||
return sig.hex()
|
return sig.hex()
|
||||||
|
|
||||||
def sign_event(self, event: Event) -> None:
|
def sign_event(self, event: Event) -> None:
|
||||||
|
|
@ -131,9 +128,7 @@ class PrivateKey:
|
||||||
return self.raw_secret == other.raw_secret
|
return self.raw_secret == other.raw_secret
|
||||||
|
|
||||||
|
|
||||||
def mine_vanity_key(
|
def mine_vanity_key(prefix: str | None = None, suffix: str | None = None) -> PrivateKey:
|
||||||
prefix: Optional[str] = None, suffix: Optional[str] = None
|
|
||||||
) -> PrivateKey:
|
|
||||||
if prefix is None and suffix is None:
|
if prefix is None and suffix is None:
|
||||||
raise ValueError("Expected at least one of 'prefix' or 'suffix' arguments")
|
raise ValueError("Expected at least one of 'prefix' or 'suffix' arguments")
|
||||||
|
|
||||||
|
|
@ -149,14 +144,3 @@ def mine_vanity_key(
|
||||||
break
|
break
|
||||||
|
|
||||||
return sk
|
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"
|
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."
|
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]
|
[tool.poetry]
|
||||||
python = "^3.10 | ^3.9"
|
package-mode = false
|
||||||
lnbits = {allow-prereleases = true, version = "*"}
|
|
||||||
|
|
||||||
[tool.poetry.group.dev.dependencies]
|
[tool.uv]
|
||||||
black = "^24.3.0"
|
dev-dependencies = [
|
||||||
pytest-asyncio = "^0.21.0"
|
"black",
|
||||||
pytest = "^7.3.2"
|
"pytest-asyncio",
|
||||||
mypy = "^1.5.1"
|
"pytest",
|
||||||
pre-commit = "^3.2.2"
|
"mypy",
|
||||||
ruff = "^0.3.2"
|
"pre-commit",
|
||||||
types-cffi = "^1.16.0.20240331"
|
"ruff",
|
||||||
pytest-md = "^0.2.0"
|
"pytest-md",
|
||||||
|
"types-cffi",
|
||||||
[build-system]
|
]
|
||||||
requires = ["poetry-core>=1.0.0"]
|
|
||||||
build-backend = "poetry.core.masonry.api"
|
|
||||||
|
|
||||||
[tool.mypy]
|
[tool.mypy]
|
||||||
exclude = "(nostr/*)"
|
exclude = "(nostr/*)"
|
||||||
|
plugins = ["pydantic.mypy"]
|
||||||
|
|
||||||
[[tool.mypy.overrides]]
|
[[tool.mypy.overrides]]
|
||||||
module = [
|
module = [
|
||||||
"nostr.*",
|
"nostr.*",
|
||||||
"lnbits.*",
|
|
||||||
"lnurl.*",
|
|
||||||
"loguru.*",
|
|
||||||
"fastapi.*",
|
|
||||||
"pydantic.*",
|
|
||||||
"pyqrcode.*",
|
|
||||||
"shortuuid.*",
|
|
||||||
"httpx.*",
|
|
||||||
"secp256k1.*",
|
|
||||||
"websocket.*",
|
|
||||||
]
|
]
|
||||||
follow_imports = "skip"
|
follow_imports = "skip"
|
||||||
ignore_missing_imports = "True"
|
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]
|
[tool.pytest.ini_options]
|
||||||
log_cli = false
|
log_cli = false
|
||||||
testpaths = [
|
testpaths = [
|
||||||
|
|
|
||||||
18
router.py
18
router.py
|
|
@ -1,6 +1,6 @@
|
||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
from typing import ClassVar, Dict, List
|
from typing import ClassVar
|
||||||
|
|
||||||
from fastapi import WebSocket, WebSocketDisconnect
|
from fastapi import WebSocket, WebSocketDisconnect
|
||||||
from lnbits.helpers import urlsafe_short_hash
|
from lnbits.helpers import urlsafe_short_hash
|
||||||
|
|
@ -16,7 +16,7 @@ all_routers: list["NostrRouter"] = []
|
||||||
|
|
||||||
|
|
||||||
class 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_notices: ClassVar[list[NoticeMessage]] = []
|
||||||
received_subscription_eosenotices: ClassVar[dict[str, EndOfStoredEventsMessage]] = (
|
received_subscription_eosenotices: ClassVar[dict[str, EndOfStoredEventsMessage]] = (
|
||||||
{}
|
{}
|
||||||
|
|
@ -25,11 +25,11 @@ class NostrRouter:
|
||||||
def __init__(self, websocket: WebSocket):
|
def __init__(self, websocket: WebSocket):
|
||||||
self.connected: bool = True
|
self.connected: bool = True
|
||||||
self.websocket: WebSocket = websocket
|
self.websocket: WebSocket = websocket
|
||||||
self.tasks: List[asyncio.Task] = []
|
self.tasks: list[asyncio.Task] = []
|
||||||
self.original_subscription_ids: Dict[str, str] = {}
|
self.original_subscription_ids: dict[str, str] = {}
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def subscriptions(self) -> List[str]:
|
def subscriptions(self) -> list[str]:
|
||||||
return list(self.original_subscription_ids.keys())
|
return list(self.original_subscription_ids.keys())
|
||||||
|
|
||||||
def start(self):
|
def start(self):
|
||||||
|
|
@ -111,10 +111,14 @@ class NostrRouter:
|
||||||
# this reconstructs the original response from the relay
|
# this reconstructs the original response from the relay
|
||||||
# reconstruct original subscription id
|
# reconstruct original subscription id
|
||||||
s_original = self.original_subscription_ids[s]
|
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)
|
await self.websocket.send_text(event_to_forward)
|
||||||
except Exception as e:
|
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):
|
def _handle_notices(self):
|
||||||
while len(NostrRouter.received_subscription_notices):
|
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: [
|
predefinedRelays: [
|
||||||
'wss://relay.damus.io',
|
'wss://relay.damus.io',
|
||||||
'wss://nostr-pub.wellorder.net',
|
'wss://nostr-pub.wellorder.net',
|
||||||
'wss://nostr.zebedee.cloud',
|
'wss://relay.nostrconnect.com',
|
||||||
'wss://nodestr.fmt.wiz.biz',
|
|
||||||
'wss://nostr.oxtr.dev',
|
'wss://nostr.oxtr.dev',
|
||||||
'wss://nostr.wine'
|
'wss://nostr.wine'
|
||||||
]
|
]
|
||||||
|
|
@ -477,11 +476,7 @@
|
||||||
getRelays: function () {
|
getRelays: function () {
|
||||||
var self = this
|
var self = this
|
||||||
LNbits.api
|
LNbits.api
|
||||||
.request(
|
.request('GET', '/nostrclient/api/v1/relays')
|
||||||
'GET',
|
|
||||||
'/nostrclient/api/v1/relays?usr=' + this.g.user.id,
|
|
||||||
this.g.user.wallets[0].adminkey
|
|
||||||
)
|
|
||||||
.then(function (response) {
|
.then(function (response) {
|
||||||
if (response.data) {
|
if (response.data) {
|
||||||
response.data.map(maplrelays)
|
response.data.map(maplrelays)
|
||||||
|
|
@ -509,12 +504,9 @@
|
||||||
console.log('ADD RELAY ' + this.relayToAdd)
|
console.log('ADD RELAY ' + this.relayToAdd)
|
||||||
let that = this
|
let that = this
|
||||||
LNbits.api
|
LNbits.api
|
||||||
.request(
|
.request('POST', '/nostrclient/api/v1/relay', null, {
|
||||||
'POST',
|
url: this.relayToAdd
|
||||||
'/nostrclient/api/v1/relay?usr=' + this.g.user.id,
|
})
|
||||||
this.g.user.wallets[0].adminkey,
|
|
||||||
{url: this.relayToAdd}
|
|
||||||
)
|
|
||||||
.then(function (response) {
|
.then(function (response) {
|
||||||
console.log('response:', response)
|
console.log('response:', response)
|
||||||
if (response.data) {
|
if (response.data) {
|
||||||
|
|
@ -541,12 +533,7 @@
|
||||||
},
|
},
|
||||||
deleteRelay(url) {
|
deleteRelay(url) {
|
||||||
LNbits.api
|
LNbits.api
|
||||||
.request(
|
.request('DELETE', '/nostrclient/api/v1/relay', null, {url: url})
|
||||||
'DELETE',
|
|
||||||
'/nostrclient/api/v1/relay?usr=' + this.g.user.id,
|
|
||||||
this.g.user.wallets[0].adminkey,
|
|
||||||
{url: url}
|
|
||||||
)
|
|
||||||
.then(response => {
|
.then(response => {
|
||||||
const relayIndex = this.nostrrelayLinks.indexOf(r => r.url === url)
|
const relayIndex = this.nostrrelayLinks.indexOf(r => r.url === url)
|
||||||
if (relayIndex !== -1) {
|
if (relayIndex !== -1) {
|
||||||
|
|
@ -562,8 +549,7 @@
|
||||||
try {
|
try {
|
||||||
const {data} = await LNbits.api.request(
|
const {data} = await LNbits.api.request(
|
||||||
'GET',
|
'GET',
|
||||||
'/nostrclient/api/v1/config',
|
'/nostrclient/api/v1/config'
|
||||||
this.g.user.wallets[0].adminkey
|
|
||||||
)
|
)
|
||||||
this.config.data = data
|
this.config.data = data
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
@ -575,7 +561,7 @@
|
||||||
const {data} = await LNbits.api.request(
|
const {data} = await LNbits.api.request(
|
||||||
'PUT',
|
'PUT',
|
||||||
'/nostrclient/api/v1/config',
|
'/nostrclient/api/v1/config',
|
||||||
this.g.user.wallets[0].adminkey,
|
null,
|
||||||
this.config.data
|
this.config.data
|
||||||
)
|
)
|
||||||
this.config.data = data
|
this.config.data = data
|
||||||
|
|
@ -624,7 +610,7 @@
|
||||||
const {data} = await LNbits.api.request(
|
const {data} = await LNbits.api.request(
|
||||||
'PUT',
|
'PUT',
|
||||||
'/nostrclient/api/v1/relay/test',
|
'/nostrclient/api/v1/relay/test',
|
||||||
this.g.user.wallets[0].adminkey,
|
null,
|
||||||
{
|
{
|
||||||
sender_private_key: this.testData.senderPrivateKey,
|
sender_private_key: this.testData.senderPrivateKey,
|
||||||
reciever_public_key: this.testData.recieverPublicKey,
|
reciever_public_key: this.testData.recieverPublicKey,
|
||||||
|
|
|
||||||
8
views.py
8
views.py
|
|
@ -1,6 +1,7 @@
|
||||||
from fastapi import APIRouter, Depends, Request
|
from fastapi import APIRouter, Depends, Request
|
||||||
from fastapi.responses import HTMLResponse
|
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.decorators import check_admin
|
||||||
from lnbits.helpers import template_renderer
|
from lnbits.helpers import template_renderer
|
||||||
|
|
||||||
|
|
@ -12,7 +13,10 @@ def nostr_renderer():
|
||||||
|
|
||||||
|
|
||||||
@nostrclient_generic_router.get("/", response_class=HTMLResponse)
|
@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(
|
return nostr_renderer().TemplateResponse(
|
||||||
"nostrclient/index.html", {"request": request, "user": user.json()}
|
"nostrclient/index.html", {"request": request, "user": user.json()}
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -131,7 +131,7 @@ async def ws_relay(ws_id: str, websocket: WebSocket) -> None:
|
||||||
else:
|
else:
|
||||||
if not config.private_ws:
|
if not config.private_ws:
|
||||||
raise ValueError("Private websocket connections not accepted.")
|
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.")
|
raise ValueError("Invalid websocket endpoint.")
|
||||||
|
|
||||||
await websocket.accept()
|
await websocket.accept()
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue