Compare commits

..
Author SHA1 Message Date
Tiago Vasconcelos 139bd96639 chore: bundle 2026-07-14 16:25:28 +01:00
Tiago Vasconcelos f6114fc33a update i18n 2026-07-14 16:12:08 +01:00
Tiago Vasconcelos 399e01c6a8 reduce ui inline conditionals 2026-07-14 16:12:08 +01:00
Tiago Vasconcelos abe1e2fb27 display expiry on ACL tokens 2026-07-14 16:12:08 +01:00
43900dd6da feat: add emailConfigured to PublicSettings (#4047)
Co-authored-by: Vlad Stan <stan.v.vlad@gmail.com>
2026-07-13 15:28:28 +02:00
Riccardo BalboandGitHub 06c553219a Merge commit from fork
* fix: daily withdrawal limit

* feat: unit tests for cumulative daily withdrawal
2026-07-13 11:59:49 +03:00
fc73d83bd9 feat: optimise Uvicorn Settings for heavy web socket use (#4028)
Co-authored-by: dadofsambonzuki <dadofsambonzuki@users.noreply.github.com>
Co-authored-by: dni <office@dnilabs.com>
2026-07-13 10:28:34 +02:00
Riccardo BalboandGitHub 4cb743d952 Merge commit from fork 2026-07-13 11:25:08 +03:00
dni ⚡andGitHub 3b6e87b060 fix: docker image dont rebuild after restart (#4057) 2026-07-13 11:17:28 +03:00
dni ⚡andGitHub 09e44f18e5 test: fix revolut test timestamp exceeded (#4054) 2026-07-13 10:53:17 +03:00
24 changed files with 199 additions and 89 deletions
+1 -1
View File
@@ -43,4 +43,4 @@ ENV LNBITS_HOST="0.0.0.0"
EXPOSE 5000
CMD ["sh", "-c", "uv --offline run lnbits --port $LNBITS_PORT --host $LNBITS_HOST --forwarded-allow-ips='*'"]
CMD ["sh", "-c", "uv --offline run --no-sync lnbits --port $LNBITS_PORT --host $LNBITS_HOST --forwarded-allow-ips='*'"]
+12 -46
View File
@@ -386,6 +386,7 @@ def register_custom_extensions_path():
upgrades_dir = settings.lnbits_extensions_upgrade_path
shutil.rmtree(upgrades_dir, True)
Path(upgrades_dir).mkdir(parents=True, exist_ok=True)
sys.path.append(str(upgrades_dir))
if settings.has_default_extension_path:
return
@@ -440,54 +441,10 @@ def register_ext_tasks(ext: Extension) -> None:
def register_ext_routes(app: FastAPI, ext: Extension) -> None:
"""Register FastAPI routes for extension."""
module_name = ext.module_name
# Clear all cached sub-modules so a fresh import picks up new files from ext_dir.
# A simple reload() would reuse cached sub-modules (e.g. views_api) and serve
# stale code even after the extension files have been replaced on disk.
stale = [
k for k in sys.modules if k == module_name or k.startswith(f"{module_name}.")
]
for k in stale:
del sys.modules[k]
if stale:
# Pydantic v1 keeps a global _FUNCS set of validator qualnames to detect
# duplicates. Clear the extension's entries so reimport doesn't raise
# "duplicate validator" errors for validators with the same qualname.
try:
import pydantic.class_validators as _pydantic_cv
_pydantic_cv._FUNCS = {
f for f in _pydantic_cv._FUNCS if not f.startswith(f"{module_name}.")
}
except (ImportError, AttributeError):
pass
ext_module = importlib.import_module(module_name)
ext_module = importlib.import_module(ext.module_name)
ext_route = getattr(ext_module, f"{ext.code}_ext")
ext_redirects = (
getattr(ext_module, f"{ext.code}_redirect_paths")
if hasattr(ext_module, f"{ext.code}_redirect_paths")
else []
)
settings.activate_extension_paths(ext.code, ext_redirects)
# Remove existing routes for this extension before re-registering so that
# an upgraded extension replaces the old one at the same paths (no prefix).
ext_prefix = f"/{ext.code}"
app.router.routes = [
r
for r in app.router.routes
if not (
getattr(r, "path", "") == ext_prefix
or getattr(r, "path", "").startswith(f"{ext_prefix}/")
)
]
# Invalidate FastAPI's cached OpenAPI schema so the next /openapi.json
# request reflects the updated routes.
app.openapi_schema = None
if hasattr(ext_module, f"{ext.code}_static_files"):
ext_statics = getattr(ext_module, f"{ext.code}_static_files")
for s in ext_statics:
@@ -496,8 +453,17 @@ def register_ext_routes(app: FastAPI, ext: Extension) -> None:
)
app.mount(s["path"], StaticFiles(directory=static_dir), s["name"])
ext_redirects = (
getattr(ext_module, f"{ext.code}_redirect_paths")
if hasattr(ext_module, f"{ext.code}_redirect_paths")
else []
)
settings.activate_extension_paths(ext.code, ext.upgrade_hash, ext_redirects)
logger.trace(f"Adding route for extension {ext_module}.")
app.include_router(router=ext_route)
prefix = f"/upgrades/{ext.upgrade_hash}" if ext.upgrade_hash != "" else ""
app.include_router(router=ext_route, prefix=prefix)
async def check_and_register_extensions(app: FastAPI) -> None:
+5
View File
@@ -1,5 +1,6 @@
import asyncio
import importlib
import sys
import time
from functools import wraps
from getpass import getpass
@@ -376,6 +377,10 @@ async def extensions_update( # noqa: C901
if not await _can_run_operation(url):
return
upgrades_dir = settings.lnbits_extensions_upgrade_path
Path(upgrades_dir).mkdir(parents=True, exist_ok=True)
sys.path.append(str(upgrades_dir))
if extension:
await update_extension(extension, repo_index, source_repo, url, admin_user)
return
+12 -1
View File
@@ -147,13 +147,21 @@ class Extension(BaseModel):
name: str | None = None
short_description: str | None = None
tile: str | None = None
upgrade_hash: str | None = ""
@property
def module_name(self) -> str:
if self.is_upgrade_extension:
return f"{self.code}-{self.upgrade_hash}"
if settings.has_default_extension_path:
return f"lnbits.extensions.{self.code}"
return self.code
@property
def is_upgrade_extension(self) -> bool:
return self.upgrade_hash != ""
@classmethod
def from_installable_ext(cls, ext_info: InstallableExtension) -> Extension:
return Extension(
@@ -162,6 +170,7 @@ class Extension(BaseModel):
name=ext_info.name,
short_description=ext_info.short_description,
tile=ext_info.icon,
upgrade_hash=ext_info.hash if ext_info.ext_upgrade_dir.is_dir() else "",
)
@@ -366,6 +375,9 @@ class InstallableExtension(BaseModel):
@property
def module_name(self) -> str:
if self.ext_upgrade_dir.is_dir():
return f"{self.id}-{self.hash}"
if settings.has_default_extension_path:
return f"lnbits.extensions.{self.id}"
return self.id
@@ -456,7 +468,6 @@ class InstallableExtension(BaseModel):
shutil.rmtree(self.ext_dir, True)
shutil.copytree(Path(self.ext_upgrade_dir), Path(self.ext_dir))
shutil.rmtree(self.ext_upgrade_dir, True)
logger.info(f"Extension {self.name} ({self.installed_version}) extracted.")
def clean_extension_files(self):
+1
View File
@@ -41,6 +41,7 @@ class SimpleStatus(BaseModel):
class SimpleItem(BaseModel):
id: str
name: str
expires_at: int | None = None
class DbVersion(BaseModel):
+19 -15
View File
@@ -56,10 +56,14 @@ async def install_extension(
else:
await update_installed_extension(ext_info)
if installed_ext:
extension = Extension.from_installable_ext(ext_info)
if extension.is_upgrade_extension:
# call stop while the old routes are still active
await stop_extension_background_work(ext_info.id)
return Extension.from_installable_ext(ext_info)
await start_extension_background_work(ext_info.id)
return extension
async def check_extensions_limit(installed_ext: InstallableExtension | None = None):
@@ -99,16 +103,16 @@ async def stop_extension_background_work(ext_id: str) -> bool:
Stop background work for extension (like asyncio.Tasks, WebSockets, etc).
Extension must expose a `myextension_stop()` function if it is starting tasks.
"""
ext = Extension(code=ext_id, is_valid=True)
module_name = ext.module_name
upgrade_hash = settings.extension_upgrade_hash(ext_id)
ext = Extension(code=ext_id, is_valid=True, upgrade_hash=upgrade_hash)
try:
logger.info(f"Stopping background work for extension '{module_name}'.")
old_module = importlib.import_module(module_name)
logger.info(f"Stopping background work for extension '{ext.module_name}'.")
old_module = importlib.import_module(ext.module_name)
stop_fn_name = f"{ext_id}_stop"
if not hasattr(old_module, stop_fn_name):
raise ValueError(f"No stop function found for '{module_name}'.")
raise ValueError(f"No stop function found for '{ext.module_name}'.")
stop_fn = getattr(old_module, stop_fn_name)
if stop_fn:
@@ -116,9 +120,9 @@ async def stop_extension_background_work(ext_id: str) -> bool:
await stop_fn()
else:
stop_fn()
logger.info(f"Stopped background work for extension '{module_name}'.")
logger.info(f"Stopped background work for extension '{ext.module_name}'.")
except Exception as ex:
logger.warning(f"Failed to stop background work for '{module_name}'.")
logger.warning(f"Failed to stop background work for '{ext.module_name}'.")
logger.warning(ex)
return False
@@ -131,12 +135,12 @@ async def start_extension_background_work(ext_id: str) -> bool:
Extension CAN expose a `myextension_start()` function if it is starting tasks.
Extension MUST expose a `myextension_stop()` in that case.
"""
ext = Extension(code=ext_id, is_valid=True)
module_name = ext.module_name
upgrade_hash = settings.extension_upgrade_hash(ext_id)
ext = Extension(code=ext_id, is_valid=True, upgrade_hash=upgrade_hash)
try:
logger.info(f"Starting background work for extension '{module_name}'.")
new_module = importlib.import_module(module_name)
logger.info(f"Starting background work for extension '{ext.module_name}'.")
new_module = importlib.import_module(ext.module_name)
start_fn_name = f"{ext_id}_start"
# start function is optional, return False if not found
@@ -149,10 +153,10 @@ async def start_extension_background_work(ext_id: str) -> bool:
await start_fn()
else:
start_fn()
logger.info(f"Started background work for extension '{module_name}'.")
logger.info(f"Started background work for extension '{ext.module_name}'.")
return True
except Exception as ex:
logger.warning(f"Failed to start background work for '{module_name}'.")
logger.warning(f"Failed to start background work for '{ext.module_name}'.")
logger.warning(ex)
return False
+2 -3
View File
@@ -17,7 +17,7 @@ from lnbits.db import Connection, Filters
from lnbits.decorators import check_user_extension_access
from lnbits.exceptions import InvoiceError, PaymentError, UnsupportedError
from lnbits.fiat import get_fiat_provider
from lnbits.helpers import check_callback_url
from lnbits.helpers import check_callback_url, daystart_timestamp
from lnbits.settings import settings
from lnbits.task_manager import task_manager
from lnbits.utils.crypto import fake_privkey, random_secret_and_hash, verify_preimage
@@ -557,10 +557,9 @@ async def check_wallet_daily_withdraw_limit(
raise ValueError("It is not allowed to spend funds from this server.")
payments = await get_payments(
since=int(time.time()) - 60 * 60 * 24,
since=daystart_timestamp(),
outgoing=True,
wallet_id=wallet_id,
limit=1,
conn=conn,
)
if len(payments) == 0:
+4 -1
View File
@@ -295,7 +295,10 @@ async def api_create_user_api_token(
account.username, api_token_id, data.expiration_time_minutes
)
acl.token_id_list.append(SimpleItem(id=api_token_id, name=data.token_name))
expires_at = int(time()) + data.expiration_time_minutes * 60
acl.token_id_list.append(
SimpleItem(id=api_token_id, name=data.token_name, expires_at=expires_at)
)
await update_user_access_control_list(acls)
return ApiTokenResponse(id=api_token_id, api_token=api_token)
+5 -4
View File
@@ -158,10 +158,6 @@ async def api_update_user(
async def api_users_delete_user(
user_id: str, account: Account = Depends(check_admin)
) -> SimpleStatus:
wallets = await get_wallets(user_id, deleted=False)
for wallet in wallets:
await delete_wallet_by_id(wallet.id)
if user_id == settings.super_user:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
@@ -173,6 +169,11 @@ async def api_users_delete_user(
status_code=HTTPStatus.BAD_REQUEST,
detail="Only super_user can delete admin user.",
)
wallets = await get_wallets(user_id, deleted=False)
for wallet in wallets:
await delete_wallet_by_id(wallet.id)
await delete_account(user_id)
return SimpleStatus(success=True, message="User deleted.")
+16 -1
View File
@@ -310,7 +310,12 @@ def get_api_routes(routes: list) -> dict[str, str]:
def path_segments(path: str) -> list[str]:
path = path.strip("/")
return path.split("/")
segments = path.split("/")
if len(segments) < 2:
return segments
if segments[0] == "upgrades":
return segments[2:]
return segments[0:]
def normalize_path(path: str | None) -> str:
@@ -367,3 +372,13 @@ def sha256s(value: str) -> str:
Returns the hex as a string.
"""
return hashlib.sha256(value.encode("utf-8")).hexdigest()
def daystart_timestamp(dt: datetime | None = None) -> int:
"""
Returns the timestamp of the start of the day for the given
datetime (or now in UTC if not provided).
"""
dt = dt or datetime.now(timezone.utc)
day_start = dt.replace(hour=0, minute=0, second=0, microsecond=0)
return int(day_start.timestamp())
+8
View File
@@ -51,6 +51,14 @@ class InstalledExtensionMiddleware:
await self.app(scope, receive, send)
return
# re-route all trafic if the extension has been upgraded
if top_path in settings.lnbits_upgraded_extensions:
upgrade_path = (
f"""{settings.lnbits_upgraded_extensions[top_path]}/{top_path}"""
)
tail = "/".join(rest)
scope["path"] = f"/upgrades/{upgrade_path}/{tail}"
await self.app(scope, receive, send)
def _response_by_accepted_type(
+6
View File
@@ -27,6 +27,8 @@ from lnbits.settings import set_cli_settings, settings
@click.option(
"--reload", is_flag=True, default=False, help="Enable auto-reload for development"
)
@click.option("--ws-max-queue", default=128, help="Websocket max queue size")
@click.option("--ws-ping-timeout", default=60.0, help="Websocket ping timeout")
def main(
port: int,
host: str,
@@ -34,6 +36,8 @@ def main(
ssl_keyfile: str,
ssl_certfile: str,
reload: bool,
ws_max_queue: int,
ws_ping_timeout: float,
):
"""Launched with `uv run lnbits` at root level"""
@@ -58,6 +62,8 @@ def main(
ssl_keyfile=ssl_keyfile,
ssl_certfile=ssl_certfile,
reload=reload or False,
ws_ping_timeout=ws_ping_timeout,
ws_max_queue=ws_max_queue,
)
server = uvicorn.Server(config=config)
+20
View File
@@ -166,6 +166,8 @@ class ExchangeRateProvider(BaseModel):
class InstalledExtensionsSettings(LNbitsSettings):
# installed extensions that have been deactivated
lnbits_deactivated_extensions: set[str] = Field(default=set())
# upgraded extensions that require API redirects
lnbits_upgraded_extensions: dict[str, str] = Field(default={})
# list of redirects that extensions want to perform
lnbits_extensions_redirects: list[RedirectPath] = Field(default=[])
@@ -188,10 +190,18 @@ class InstalledExtensionsSettings(LNbitsSettings):
def activate_extension_paths(
self,
ext_id: str,
upgrade_hash: str | None = None,
ext_redirects: list[dict] | None = None,
):
self.lnbits_deactivated_extensions.discard(ext_id)
"""
Update the list of upgraded extensions. The middleware will perform
redirects based on this
"""
if upgrade_hash:
self.lnbits_upgraded_extensions[ext_id] = upgrade_hash
if ext_redirects:
self._activate_extension_redirects(ext_id, ext_redirects)
@@ -201,6 +211,9 @@ class InstalledExtensionsSettings(LNbitsSettings):
self.lnbits_deactivated_extensions.add(ext_id)
self._remove_extension_redirects(ext_id)
def extension_upgrade_hash(self, ext_id: str) -> str:
return settings.lnbits_upgraded_extensions.get(ext_id, "")
def _activate_extension_redirects(self, ext_id: str, ext_redirects: list[dict]):
ext_redirect_paths = [
RedirectPath(**{"ext_id": ext_id, **er}) for er in ext_redirects
@@ -483,6 +496,11 @@ class NotificationsSettings(LNbitsSettings):
and self.lnbits_telegram_notifications_access_token is not None
)
def is_email_notifications_configured(self) -> bool:
return self.lnbits_email_notifications_enabled and bool(
self.lnbits_email_notifications_email
)
class FakeWalletFundingSource(LNbitsSettings):
fake_wallet_secret: str = Field(default="ToTheMoon1")
@@ -1282,6 +1300,7 @@ class PublicSettings(BaseModel):
extensions_reviews_url: str = Field(alias="extensionsReviewsUrl")
ext_builder: bool = Field(alias="extBuilder")
nostr_configured: bool = Field(alias="nostrConfigured")
email_configured: bool = Field(alias="emailConfigured")
telegram_configured: bool = Field(alias="telegramConfigured")
wallet_featured_button_label: str | None = Field(alias="walletFeaturedButtonLabel")
wallet_featured_button_url: str | None = Field(alias="walletFeaturedButtonUrl")
@@ -1346,6 +1365,7 @@ class PublicSettings(BaseModel):
extensionsReviewsUrl=settings.lnbits_extensions_reviews_url,
extBuilder=settings.lnbits_extensions_builder_activate_non_admins,
nostrConfigured=settings.is_nostr_notifications_configured(),
emailConfigured=settings.is_email_notifications_configured(),
telegramConfigured=settings.is_telegram_notifications_configured(),
walletFeaturedButtonLabel=settings.lnbits_wallet_featured_button_label,
walletFeaturedButtonUrl=settings.lnbits_wallet_featured_button_url,
File diff suppressed because one or more lines are too long
+1 -1
View File
File diff suppressed because one or more lines are too long
+2
View File
@@ -482,6 +482,8 @@ window.localisation.en = {
access_control_list_admin_warning:
'This is an admin account. The generated tokens will have admin privileges.',
new_api_acl: 'New Access Control List',
acl_token_active: 'Active',
acl_token_expired: 'Expired',
api_token_id: 'Token Id',
toggle_gradient: 'Toggle Gradient',
gradient_background: 'Gradient Background',
+29
View File
@@ -217,6 +217,35 @@ window.PageAccount = {
computed: {
isUserTouched() {
return !_.isEqual(this.g.user, this.untouchedUser)
},
selectedApiToken() {
return this.selectedApiAcl.token_id_list.find(
token => token.id === this.apiAcl.selectedTokenId
)
},
expiryAt() {
if (this.selectedApiToken.expires_at) {
return `${this.$t('expiry')}: ${LNbits.utils.formatTimestamp(this.selectedApiToken.expires_at)}`
} else {
return ''
}
},
tokenStatus() {
if (this.selectedApiToken.expires_at) {
const now = new Date()
const expiresAt = new Date(this.selectedApiToken.expires_at * 1000)
let status = ''
let badgeColor = 'positive'
if (expiresAt < now) {
status = this.$t('acl_token_expired')
badgeColor = 'negative'
} else {
status = this.$t('acl_token_active')
}
return {status, badgeColor}
} else {
return ''
}
}
},
methods: {
+11
View File
@@ -889,6 +889,17 @@
></q-btn>
</div>
</div>
<div
v-if="selectedApiToken && selectedApiToken.expires_at"
class="row items-center q-mb-md q-gutter-sm"
>
<span v-text="expiryAt"></span>
<span v-text="$t('status') + ':'"></span>
<q-badge
:color="tokenStatus.badgeColor"
:label="tokenStatus.status"
></q-badge>
</div>
<div v-if="apiAcl.apiToken" class="row q-mb-md">
<div class="col-12">
<q-badge>
+7 -3
View File
@@ -1745,10 +1745,14 @@ async def test_api_create_user_api_token_success(
), "Expiration time should be 60 minutes from now."
token_id = payload["api_token_id"]
assert any(
token_id in [token.id for token in acl.token_id_list]
stored_token = next(
token
for acl in acls.access_control_list
), "API token should be part of at least one ACL."
for token in acl.token_id_list
if token.id == token_id
)
assert stored_token.expires_at is not None
assert abs(stored_token.expires_at - expiration_time) <= 1
@pytest.mark.anyio
+8 -3
View File
@@ -1433,7 +1433,7 @@ def test_check_revolut_signature_multiple_v1_headers():
check_revolut_signature(payload, sig_header, timestamp, secret)
def test_check_revolut_signature_docs_vector():
def test_check_revolut_signature_docs_vector(mocker: MockerFixture):
payload = (
b'{"data":{"id":"645a7696-22f3-aa47-9c74-cbae0449cc46",'
b'"new_state":"completed","old_state":"pending",'
@@ -1445,9 +1445,14 @@ def test_check_revolut_signature_docs_vector():
secret = "wsk_r59a4HfWVAKycbCaNO1RvgCJec02gRd8"
sig = "v1=bca326fb378d0da7f7c490ad584a8106bab9723d8d9cdd0d50b4c5b3be3837c0"
check_revolut_signature(
payload, sig, timestamp, secret, tolerance_seconds=100000000
# This is a fixed vector straight from Revolut's docs, so its timestamp is
# necessarily in the past. Freeze time to it instead of growing
# tolerance_seconds indefinitely as real time marches on.
mocker.patch(
"lnbits.core.services.fiat_providers.time.time",
return_value=int(timestamp) / 1000,
)
check_revolut_signature(payload, sig, timestamp, secret)
@pytest.mark.anyio
+2
View File
@@ -259,7 +259,9 @@ def test_get_api_routes_extracts_v1_paths():
def test_path_and_case_helpers():
assert path_segments("/wallet/path") == ["wallet", "path"]
assert path_segments("/upgrades/ext/assets/app.js") == ["assets", "app.js"]
assert normalize_path(None) == "/"
assert normalize_path("/upgrades/ext/assets/app.js") == "/assets/app.js"
assert normalize_endpoint("example.com/") == "https://example.com"
assert normalize_endpoint("ws://socket.example.com") == "ws://socket.example.com"
assert (
+3 -8
View File
@@ -62,9 +62,6 @@ async def test_install_extension_creates_new_extension_and_starts_background_wor
"lnbits.core.services.extensions.start_extension_background_work",
mocker.AsyncMock(return_value=True),
)
mocker.patch(
"lnbits.core.services.extensions.core_app_extra.register_new_ext_routes"
)
mocker.patch(
"lnbits.core.services.extensions.get_db_version",
mocker.AsyncMock(return_value=0),
@@ -79,7 +76,6 @@ async def test_install_extension_creates_new_extension_and_starts_background_wor
settings.lnbits_extensions_path = str(tmp_path / "code")
extension = await install_extension(ext_info)
await activate_extension(extension) # starts background task
stored = await get_installed_extension(ext_id)
finally:
await delete_installed_extension(ext_id=ext_id)
@@ -115,9 +111,6 @@ async def test_install_extension_updates_existing_upgrade_and_preserves_payments
"lnbits.core.services.extensions.stop_extension_background_work",
mocker.AsyncMock(return_value=True),
)
mocker.patch(
"lnbits.core.services.extensions.core_app_extra.register_new_ext_routes"
)
mocker.patch(
"lnbits.core.services.extensions.get_db_version",
mocker.AsyncMock(return_value=1),
@@ -131,8 +124,9 @@ async def test_install_extension_updates_existing_upgrade_and_preserves_payments
settings.lnbits_data_folder = str(tmp_path / "data")
settings.lnbits_extensions_path = str(tmp_path / "code")
await create_installed_extension(existing_ext)
updated_ext.ext_upgrade_dir.mkdir(parents=True, exist_ok=True)
extension = await install_extension(updated_ext, skip_download=True)
await activate_extension(extension) # starts background task
stored = await get_installed_extension(ext_id)
finally:
await delete_installed_extension(ext_id=ext_id)
@@ -140,6 +134,7 @@ async def test_install_extension_updates_existing_upgrade_and_preserves_payments
settings.lnbits_extensions_path = original_extensions_path
assert extension.code == ext_id
assert extension.is_upgrade_extension is True
assert stored is not None
assert stored.meta is not None
assert stored.meta.payments == [existing_payment]
+18
View File
@@ -27,6 +27,7 @@ from lnbits.core.services.payments import (
check_pending_payments,
check_time_limit_between_transactions,
check_transaction_status,
check_wallet_daily_withdraw_limit,
check_wallet_limits,
create_payment_request,
get_payments_daily_stats,
@@ -248,6 +249,23 @@ async def test_check_wallet_limits_and_time_limit(
settings.lnbits_wallet_limit_secs_between_trans = original_limit
@pytest.mark.anyio
async def test_check_wallet_daily_limit_counts_all_daily_payments(settings: Settings):
wallet = await _create_wallet()
await _create_payment(wallet, amount_msat=-2_000, status=PaymentState.SUCCESS)
await _create_payment(wallet, amount_msat=-3_000, status=PaymentState.SUCCESS)
original_limit = settings.lnbits_wallet_limit_daily_max_withdraw
try:
settings.lnbits_wallet_limit_daily_max_withdraw = 5
with pytest.raises(
ValueError, match="Daily withdrawal limit of 5 sats reached."
):
await check_wallet_daily_withdraw_limit(wallet.id, 1_000)
finally:
settings.lnbits_wallet_limit_daily_max_withdraw = original_limit
@pytest.mark.anyio
async def test_calculate_fiat_amounts_handles_conversion_and_errors(
mocker: MockerFixture,
+6 -1
View File
@@ -216,11 +216,16 @@ def test_installed_extensions_settings_activate_and_deactivate_paths():
}
]
installed.activate_extension_paths("lnurlp", ext_redirects=redirects)
installed.activate_extension_paths(
"lnurlp",
upgrade_hash="hash123",
ext_redirects=redirects,
)
redirect = installed.find_extension_redirect("/.well-known/lnurlp", [])
assert redirect is not None
assert redirect.ext_id == "lnurlp"
assert installed.lnbits_upgraded_extensions["lnurlp"] == "hash123"
assert "lnurlp" in installed.lnbits_installed_extensions_ids
installed.deactivate_extension_paths("lnurlp")