What changed, and why it matters
This is a large feature commit that adds native Bitcoin on-chain wallet support to LNbits, including hot wallets whose recovery phrases are encrypted by a server-side master key. It introduces new code paths for key management, address derivation, blockchain scanning, transaction signing, and broadcasting. Because the commit is a feature addition rather than a documented security fix, the main risk is that any bugs or design weaknesses in the new on-chain subsystem could lead to loss of funds, key exposure, or incorrect balances. The diff itself does not show an obvious exploitable vulnerability, but the size and sensitivity of the code mean the change should be reviewed carefully before being trusted with real funds.
Treat this as a high-risk feature commit, not a routine dependency update. Before deploying with real funds: review the new on-chain key lifecycle (generation, backup, restore, rotation), verify that the encrypted seed is never logged or returned in API responses, audit the signing path for memory handling of plaintext mnemonics, test the super-user authorization on admin on-chain endpoints, and run the included on-chain unit and e2e tests. Consider additional code audit or fuzzing of the PSBT/extract/broadcast endpoints because they process externally supplied transaction data.
Security signals we found
New server-side hot wallet signing that decrypts BIP39 mnemonics in process
New master encryption key stored on the server filesystem and optionally in environment variables
New on-chain API surface with admin/read key scoping and super-user gating for enabling payments
New database migrations adding on-chain wallet state and a balances view that sums UTXOs for on-chain wallets
Validation added for derivation paths, transaction amounts, output networks, and broadcast responses
Sensitive endpoints set Cache-Control: no-store / Pragma: no-cache
Atomic, owner-only key file creation with a check that prevents replacing an existing key
Evidence from the diff
The commit implements core on-chain wallets as a new WalletType.ONCHAIN. It adds database migrations, models, CRUD operations, a block explorer abstraction (LNbits Electrum and Mempool), a periodic background sync task, and API endpoints for watch-only and hot wallets. Hot wallet recovery phrases are encrypted with AES using a 32-byte master key that can be generated in the UI, read from LNBITS_DATA_FOLDER/.onchain_key, or supplied via LNBITS_ONCHAIN_MASTER_KEY / WATCHONLY_MASTER_KEY. The key fingerprint is pinned in the settings database. Signing happens server-side via libwally. The patch also prevents on-chain wallets from entering the Lightning payment ledger and from having their balance manually adjusted. Several security-relevant design choices are visible: mode-0600 key file creation via atomic link, no replacement of an existing key, super-user-only enablement of on-chain payments, backup confirmation gating for hot wallet receive/send, derivation-path validation, input/output amount and network checks before signing, and cache-control no-store on sensitive responses. However, the change is large (+50k lines, mostly static assets), the signing code trusts the server with plaintext mnemonics, and the new API surface has not been externally audited in this review.
Changed components
lnbits/core/services/onchain.pylnbits/core/services/blockexplorer.pylnbits/core/views/onchain_api.pylnbits/core/views/wallet_api.pylnbits/core/views/admin_api.pylnbits/core/crud/onchain.pylnbits/core/crud/wallets.pylnbits/core/models/onchain.pylnbits/core/models/wallets.pylnbits/core/migrations.pylnbits/utils/onchain.pylnbits/utils/electrum.pylnbits/decorators.pylnbits/app.pyInspect captured patch +50244 / −78
diff --git a/.env.example b/.env.example
index f49fd70..059d038 100644
--- a/.env.example
+++ b/.env.example
@@ -60,6 +60,11 @@ PORT=5000
LNBITS_DATA_FOLDER="./data"
# LNBITS_DATABASE_URL="postgres://user:password@host:port/databasename"
+# Optional: externally managed onchain wallet encryption key (base64, 32 bytes).
+# Usually generated and backed up by the super user in Settings > Payments.
+# Keep the same key permanently; never replace it for existing wallets.
+# LNBITS_ONCHAIN_MASTER_KEY=
+
# Extensions to be installed by default. If an extension from this list is uninstalled then it will be re-installed on the next restart.
# The extension must be removed from this list in order to not be re-installed.
LNBITS_EXTENSIONS_DEFAULT_INSTALL="tpos"
diff --git a/.github/workflows/regtest.yml b/.github/workflows/regtest.yml
index e3012c2..1e7f7fa 100644
--- a/.github/workflows/regtest.yml
+++ b/.github/workflows/regtest.yml
@@ -79,9 +79,9 @@ jobs:
report-title: "regtest (${{ inputs.python-version }}, ${{ inputs.backend-wallet-class }}"
- name: Upload coverage to Codecov
- uses: codecov/codecov-action@v4
+ uses: codecov/codecov-action@v7
with:
- file: ./coverage.xml
+ files: ./coverage.xml
token: ${{ secrets.CODECOV_TOKEN }}
verbose: true
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 08cbef7..1f2270c 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -75,8 +75,8 @@ jobs:
report-title: "test (${{ inputs.python-version }}, ${{ inputs.db-url }})"
- name: Upload coverage to Codecov
- uses: codecov/codecov-action@v4
+ uses: codecov/codecov-action@v7
with:
- file: ./coverage.xml
+ files: ./coverage.xml
token: ${{ secrets.CODECOV_TOKEN }}
verbose: false
diff --git a/AGENTS.md b/AGENTS.md
index eb4aba8..7fa934e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -40,6 +40,8 @@ Use Makefile targets instead of hand-written commands when available:
Do not run `make test` by default. Use the targeted tests available in the Makefile that are related to the work done, unless the user explicitly asks for broader test coverage.
+Do not create new end-to-end (e2e) tests, including new scenarios in existing e2e suites.
+
## Dependencies
Do not add dependencies without approval. If approved, update the correct project files and explain why the dependency is necessary.
diff --git a/Makefile b/Makefile
index 4a5c38d..abf3ab7 100644
--- a/Makefile
+++ b/Makefile
@@ -169,3 +169,11 @@ install-pre-commit-hook:
pre-commit:
uv run pre-commit run --all-files
+
+# Deterministic core onchain UI and hardware protocol regressions.
+test-onchain-ui:
+ node --test tests/onchain/*.test.cjs
+
+# Requires a local Chrome/Chromium executable or Playwright browser install.
+test-onchain-browser:
+ node tests/e2e/onchain-wallet.cjs
diff --git a/docs/guide/admin_ui.md b/docs/guide/admin_ui.md
index a1fa1c7..801d70c 100644
--- a/docs/guide/admin_ui.md
+++ b/docs/guide/admin_ui.md
@@ -43,6 +43,37 @@ For a complete reference of legacy variables consult **[.env.example](../../.env
> [!NOTE]
> See **[Super User](./super_user.md)** for the role and permission differences compared to Admin Users.
+## Onchain payments and key recovery
+
+The super user can enable server-managed Bitcoin wallets in the Watchonly
+extension and core onchain wallets from **Settings → Payments → Onchain payments**:
+
+1. Select **Generate encryption key**.
+2. Download the key backup, store it securely, and confirm the backup.
+3. Enable **Allow onchain payments** and select **Save**.
+
+LNbits saves the generated key in `.onchain_key` inside `LNBITS_DATA_FOLDER` with
+owner-only file permissions. No environment variable or launch flag is required.
+The same key must be retained across restarts. All workers must share this key.
+The key encrypts hot wallet recovery phrases; it is excluded from ordinary
+settings responses. Disabling the toggle stops hot wallet creation and signing,
+while keeping wallet recovery available. Hardware/watch-only wallets are unaffected.
+
+**Download backup** includes the generated key along with the data folder. Treat
+that archive as wallet recovery material. Keep a separate key recovery file as
+well, particularly when backing up only the database. Restore the database and
+data folder together; if the key file is missing, upload the original
+`lnbits-onchain-key.json` using **Restore an encryption key** in Payments settings.
+LNbits checks the key against the database and refuses a different key. Resetting
+settings preserves the key and its backup record.
+
+Deployments using a secret manager can optionally set `LNBITS_ONCHAIN_MASTER_KEY`
+in the environment or `.env` (base64-encoded, 32 random bytes). The earlier
+`WATCHONLY_MASTER_KEY` name is also supported. Back up and confirm that key through
+the same UI before enabling hot wallets. Environment variables are not included
+in the full data-folder backup, so retain the separate key recovery file. Never
+replace a key that is already used by wallets.
+
## First run and Super User ID
On first start with the Admin UI enabled you will be prompted to generate a Super User.
diff --git a/docs/guide/wallets_onchain.md b/docs/guide/wallets_onchain.md
new file mode 100644
index 0000000..0dc9f9a
--- /dev/null
+++ b/docs/guide/wallets_onchain.md
@@ -0,0 +1,111 @@
+# Onchain wallets
+
+Choose **Onchain** in **Add wallet**, then select Mainnet, Testnet4 or Testnet3.
+Each LNbits onchain wallet holds one Bitcoin wallet on one network.
+The network badge appears in the wallet card header. Use **Set up wallet** to
+configure it; to use another Bitcoin wallet, create another LNbits onchain wallet
+from the sidebar. This limit is also enforced by the API and database.
+
+The standard wallet card shows the Bitcoin wallet details and device connection
+buttons beneath the wallet name, with a settings cog on the right. **Advanced** remains
+expandable, followed by the usual wallet configuration and tools.
+
+Add a hot wallet, import a public descriptor/account key, or connect a supported
+hardware wallet. Trezor and the existing serial hardware signing flows are
+available. Watch-only accounts receive and track bitcoin; spending requires an
+external signer. Hot wallets sign on the LNbits server.
+
+## Hot wallets and recovery
+
+The superuser enables server signing under **Settings → Payments → Onchain
+payments**. Generate or restore the encryption key, download its backup, confirm
+that it is stored safely, and enable payments. An environment key remains
+supported through `LNBITS_ONCHAIN_MASTER_KEY`; UI-generated keys are stored in the
+LNbits data directory and included in server backups.
+
+Each hot wallet also has its own recovery phrase. The Backup → Verify flow
+checks words before enabling receive/send. When creating or restoring, choose Legacy,
+Wrapped SegWit, Native SegWit (the default), or Taproot. The standard path uses account
+zero and the selected network; Native SegWit uses `m/84'/0'/0'` on Mainnet or
+`m/84'/1'/0'` on the test networks. **Custom Derivation Path** accepts a BIP32 account
+path ending in a hardened index (`'`, `h`, or `H`); receiving and change branches
+are added automatically. The address type and path are fixed after setup.
+No BIP39 passphrase is used. Save the address type and path shown in the backup
+alongside the recovery phrase, and use the same settings when restoring.
+Back up both the server encryption key/database and individual wallet phrases.
+Disabling server signing does not disable phrase export.
+
+## Balances, history and payments
+
+The server scans both receive and change addresses. Confirmations, coins and
+complete address histories persist in the core database. Refreshes run without an
+open browser. During a scan, existing transactions remain visible and wallet
+creation remains available. Failed requests preserve the previous snapshot and
+show a stale-balance notice.
+
+With the LNbits explorer selected, the wallet uses its existing block and address
+WebSockets to request updates when activity arrives. Address subscriptions cover
+the current receive address, recent receive addresses and funded addresses, up to
+eight unique addresses. A one-minute state refresh covers all remaining addresses
+and serves as the fallback for Mempool or disconnected sockets. Active scans are
+checked every ten seconds. Hidden pages pause these requests, and charts refresh
+only when confirmed activity changes after a scan finishes.
+
+Sending uses a stable copy of the selected coins and change address while the
+background view refreshes. Server signing checks that the selected coins remain
+unspent. Review the recipients, change and fee before broadcasting. If a broadcast
+request fails, check transaction status before submitting another payment.
+
+Use **Wallet Config** for fiat currency tracking, wallet naming, icons and pinning.
+The fiat equivalent and transaction fiat values use the current exchange rate.
+Charts summarize this wallet's confirmed transactions; transaction history and
+the main balance card show the same Bitcoin wallet.
+
+Bitcoin balances are separate from Lightning balances. Lightning invoices,
+LNURL/LndHub spending, virtual credit/debit and Lightning wallet sharing do not
+operate on onchain wallets. Mobile browser access, core wallet keys and onchain
+APIs are available from the standard wallet tools.
+
+## Explorer and installation
+
+Choose the provider using the settings cog beside the device buttons, then **Block explorer**. LNbits'
+built-in block explorer is the default when enabled for the wallet's Bitcoin
+network. Wallet operations reuse the shared service behind the block explorer API,
+including history, coins, fees, signing inputs and broadcasts; its public API need
+not be enabled. The administrator can select `test4` for a Testnet4 Electrum server.
+
+Alternatively, select **Mempool**. The editable URL defaults to
+`https://mempool.space`, with the appropriate test network selected automatically.
+For another Mempool server, enter its full network-specific base URL, without
+`/api` (for example `https://example.com/testnet4`). Localhost and LAN URLs are
+supported for self-hosted Mempool instances. The selection is saved per LNbits wallet; transaction and
+address links also open the selected explorer. No explorer environment variable
+is required. Use a provider you trust with address history.
+
+The native `wallycore` library is a standard LNbits dependency, installed by the
+normal dependency installation or update process. No installation extra is needed
+for onchain wallets.
+
+## Existing Watchonly wallets
+
+Watchonly remains a separate extension with its own data. Nothing is automatically
+moved, deleted or re-encrypted. To follow an existing account in core, import its
+public descriptor. To restore a hot wallet, use its recovery phrase in core's
+restore flow. Both interfaces then refer to the same Bitcoin funds; this does not
+transfer or duplicate those funds.
+
+## API access
+
+Use the core wallet's `X-API-KEY`. Read keys can list accounts, retrieve persistent
+state and obtain receive addresses. Admin keys also configure accounts, restore or
+export phrases, sign and broadcast transactions. Keys are scoped to the LNbits
+wallet, including when a user owns several wallets.
+
+- `GET /api/v1/wallet/onchain`: list accounts.
+- `GET /api/v1/onchain/state`: cached addresses, history, coins and scan status.
+- `POST /api/v1/onchain/sync`: schedule a background update.
+- `GET /api/v1/onchain/stats/daily`: confirmed transaction statistics.
+- `POST /api/v1/onchain/hot-wallet`: create/restore a hot wallet. Restoration
+ uses `X-Onchain-Recovery-Phrase` so phrases do not enter request-body audit logs.
+
+See the instance's `/docs#/Onchain` for the complete API schema.
diff --git a/lnbits/app.py b/lnbits/app.py
index fb20210..38904c1 100644
--- a/lnbits/app.py
+++ b/lnbits/app.py
@@ -36,6 +36,7 @@ from lnbits.core.services.notifications import (
enqueue_admin_notification,
process_next_notification,
)
+from lnbits.core.services.onchain import sync_wallets
from lnbits.core.services.payments import (
check_pending_payments,
fundingsource_invoice_producer,
@@ -577,6 +578,9 @@ def register_async_tasks() -> None:
# note: should be the first in task list for a bit quicker notifications
task_manager.register_invoice_listener(dispatch_payment_notification, "core")
+ # Core onchain wallets retain their snapshots when no browser is open.
+ task_manager.create_permanent_task(sync_wallets, interval=60)
+
# periodic tasks
task_manager.create_permanent_task(cache.invalidate_cache, interval=10)
task_manager.create_permanent_task(delete_expired_audit_entries, interval=60 * 60)
diff --git a/lnbits/core/__init__.py b/lnbits/core/__init__.py
index 125d923..7b9757c 100644
--- a/lnbits/core/__init__.py
+++ b/lnbits/core/__init__.py
@@ -16,6 +16,7 @@ from .views.fiat_api import fiat_router
from .views.generic import generic_router
from .views.lnurl_api import lnurl_router
from .views.node_api import node_router, public_node_router, super_node_router
+from .views.onchain_api import onchain_router
from .views.payment_api import payment_router
from .views.tinyurl_api import tinyurl_router
from .views.two_factor_api import two_factor_router
@@ -29,6 +30,7 @@ core_app = APIRouter(tags=["Core"])
def init_core_routers(app: FastAPI):
+ app.include_router(onchain_router)
app.include_router(core_app)
app.include_router(generic_router)
app.include_router(two_factor_router)
diff --git a/lnbits/core/crud/onchain.py b/lnbits/core/crud/onchain.py
new file mode 100644
index 0000000..643b518
--- /dev/null
+++ b/lnbits/core/crud/onchain.py
@@ -0,0 +1,190 @@
+import json
+
+from lnbits.core.crud.wallets import get_onchain_wallet
+from lnbits.core.db import db
+from lnbits.core.models.onchain import Address, Snapshot
+from lnbits.db import Connection, model_to_dict
+from lnbits.helpers import urlsafe_short_hash
+from lnbits.utils.onchain import derive_address
+
+ADDRESS_COLUMNS = ", ".join(Address.__fields__)
+
+
+async def create_address(address: Address, conn: Connection | None = None) -> None:
+ await (conn or db).execute(
+ f"""
+ INSERT INTO onchain_addresses ({ADDRESS_COLUMNS})
+ SELECT :id, :address, :walet_id, :amount, :branch_index,
+ :address_index, :note, :has_activity
+ FROM wallets WHERE id = :walet_id AND wallet_type = 'onchain'
+ AND onchain_wallet_kind IS NOT NULL
+ ON CONFLICT(walet_id, branch_index, address_index) DO NOTHING
+ """, # noqa: S608
+ model_to_dict(address),
+ )
+
+
+async def create_fresh_addresses(
+ wallet_id: str,
+ start_address_index: int,
+ end_address_index: int,
+ change_address=False,
+ conn: Connection | None = None,
+) -> list[Address]:
+ if start_address_index > end_address_index:
+ return []
+
+ wallet = await get_onchain_wallet(wallet_id, conn=conn)
+ if not wallet or not wallet.onchain_wallet_kind:
+ return []
+
+ branch_index = 1 if change_address else 0
+
+ for address_index in range(start_address_index, end_address_index):
+ address = await derive_address(
+ wallet.onchain_meta.masterpub, address_index, branch_index
+ )
+ assert address # TODO: why optional
+
+ addr = Address(
+ id=urlsafe_short_hash(),
+ address=address,
+ walet_id=wallet_id,
+ branch_index=branch_index,
+ address_index=address_index,
+ )
+
+ await create_address(addr, conn=conn)
+
+ # return fresh addresses
+ return await (conn or db).fetchall(
+ f"""
+ SELECT {ADDRESS_COLUMNS} FROM onchain_addresses WHERE walet_id = :walet_id
+ AND branch_index = :branch_index
+ AND address_index >= :start_address_index
+ AND address_index < :end_address_index
+ ORDER BY branch_index, address_index
+ """, # noqa: S608
+ {
+ "walet_id": wallet_id,
+ "branch_index": branch_index,
+ "start_address_index": start_address_index,
+ "end_address_index": end_address_index,
+ },
+ Address,
+ )
+
+
+async def get_address(address: str, conn: Connection | None = None) -> Address | None:
+ return await (conn or db).fetchone(
+ f"SELECT {ADDRESS_COLUMNS} FROM onchain_addresses WHERE address = :address", # noqa: S608
+ {"address": address},
+ Address,
+ )
+
+
+async def get_address_by_id(
+ address_id: str, conn: Connection | None = None
+) -> Address | None:
+ return await (conn or db).fetchone(
+ f"SELECT {ADDRESS_COLUMNS} FROM onchain_addresses WHERE id = :id", # noqa: S608
+ {"id": address_id},
+ Address,
+ )
+
+
+async def get_address_at_index(
+ wallet_id: str,
+ branch_index: int,
+ address_index: int,
+ conn: Connection | None = None,
+) -> Address | None:
+ return await (conn or db).fetchone(
+ f"""
+ SELECT {ADDRESS_COLUMNS} FROM onchain_addresses
+ WHERE walet_id = :walet_id AND branch_index = :branch_index
+ AND address_index = :address_index
+ """, # noqa: S608
+ {
+ "walet_id": wallet_id,
+ "branch_index": branch_index,
+ "address_index": address_index,
+ },
+ Address,
+ )
+
+
+async def get_last_used_address_index(
+ wallet_id: str, conn: Connection | None = None
+) -> int:
+ last_used: dict = await (conn or db).fetchone(
+ """SELECT COALESCE(MAX(address_index), -1) AS address_index
+ FROM onchain_addresses WHERE walet_id = :walet_id
+ AND branch_index = 0 AND has_activity = true""",
+ {"walet_id": wallet_id},
+ )
+ return last_used["address_index"]
+
+
+async def get_addresses(
+ wallet_id: str, conn: Connection | None = None
+) -> list[Address]:
+ return await (conn or db).fetchall(
+ f"""
+ SELECT {ADDRESS_COLUMNS} FROM onchain_addresses WHERE walet_id = :walet_id
+ ORDER BY branch_index, address_index
+ """, # noqa: S608
+ {"walet_id": wallet_id},
+ Address,
+ )
+
+
+async def update_address(address: Address, conn: Connection | None = None) -> Address:
+ await (conn or db).execute(
+ "UPDATE onchain_addresses SET note = :note WHERE id = :id",
+ {"id": address.id, "note": address.note},
+ )
+ return address
+
+
+async def get_address_snapshot(
+ address_id: str, conn: Connection | None = None
+) -> Snapshot | None:
+ return await (conn or db).fetchone(
+ """SELECT id AS address_id, transactions, utxos,
+ snapshot_checked_at AS checked_at
+ FROM onchain_addresses WHERE id = :id""",
+ {"id": address_id},
+ Snapshot,
+ )
+
+
+async def get_wallet_snapshots(
+ wallet_id: str, conn: Connection | None = None
+) -> list[Snapshot]:
+ return await (conn or db).fetchall(
+ """SELECT id AS address_id, transactions, utxos,
+ snapshot_checked_at AS checked_at
+ FROM onchain_addresses WHERE walet_id = :wallet AND snapshot_checked_at > 0""",
+ {"wallet": wallet_id},
+ Snapshot,
+ )
+
+
+async def update_address_snapshot(
+ snapshot: Snapshot, amount: int, conn: Connection | None = None
+) -> None:
+ # Update only: an in-flight scan must not recreate a removed address.
+ await (conn or db).execute(
+ """UPDATE onchain_addresses SET transactions = :transactions,
+ utxos = :utxos, snapshot_checked_at = :now, amount = :amount,
+ has_activity = has_activity OR :active WHERE id = :id""",
+ {
+ "id": snapshot.address_id,
+ "transactions": json.dumps(snapshot.transactions),
+ "utxos": json.dumps(snapshot.utxos),
+ "now": snapshot.checked_at,
+ "amount": amount,
+ "active": bool(snapshot.transactions),
+ },
+ )
diff --git a/lnbits/core/crud/payments.py b/lnbits/core/crud/payments.py
index 933ad50..6e357b2 100644
--- a/lnbits/core/crud/payments.py
+++ b/lnbits/core/crud/payments.py
@@ -246,8 +246,10 @@ async def create_payment(
status: PaymentState = PaymentState.PENDING,
conn: Connection | None = None,
) -> Payment:
+ wallet = await get_wallet(data.wallet_id, conn=conn)
+ if wallet and wallet.is_onchain_wallet:
+ raise ValueError("Onchain transactions cannot enter the Lightning ledger.")
if data.amount_msat < 0:
- wallet = await get_wallet(data.wallet_id, conn=conn)
if wallet and not wallet.can_send_payments:
raise ValueError("Wallet does not have permission to spend funds.")
diff --git a/lnbits/core/crud/settings.py b/lnbits/core/crud/settings.py
index 359a88b..1cf2a06 100644
--- a/lnbits/core/crud/settings.py
+++ b/lnbits/core/crud/settings.py
@@ -15,6 +15,7 @@ from lnbits.settings import (
)
RESET_PRESERVED_SETTINGS = (
+ "onchain_key",
"lnbits_webpush_pubkey",
"lnbits_webpush_privkey",
*FundingSourcesSettings.__fields__,
diff --git a/lnbits/core/crud/wallets.py b/lnbits/core/crud/wallets.py
index 4028508..e7457db 100644
--- a/lnbits/core/crud/wallets.py
+++ b/lnbits/core/crud/wallets.py
@@ -1,9 +1,17 @@
+import json
from datetime import datetime, timezone
from time import time
+from typing import Literal
from uuid import uuid4
from lnbits.core.db import db
-from lnbits.core.models.wallets import BaseWallet, WalletsFilters, WalletType
+from lnbits.core.models.wallets import (
+ BaseWallet,
+ OnchainConfig,
+ OnchainWallet,
+ WalletsFilters,
+ WalletType,
+)
from lnbits.db import Connection, Filters, Page
from lnbits.helpers import generate_ln_address
from lnbits.settings import settings
@@ -13,6 +21,14 @@ from lnbits.utils.exchange_rates import allowed_currencies
from ..models import Wallet
+class WalletAlreadyConfiguredError(ValueError):
+ def __init__(self):
+ super().__init__(
+ "This LNbits wallet is already configured. "
+ "Create another LNbits onchain wallet to set up another Bitcoin wallet."
+ )
+
+
async def create_wallet(
*,
user_id: str,
@@ -20,6 +36,7 @@ async def create_wallet(
wallet_type: WalletType = WalletType.LIGHTNING,
currency: str | None = None,
shared_wallet_id: str | None = None,
+ onchain_network: Literal["Mainnet", "Testnet", "Testnet4"] = "Mainnet",
conn: Connection | None = None,
) -> Wallet:
if currency is not None:
@@ -34,11 +51,14 @@ async def create_wallet(
name=wallet_name or settings.lnbits_default_wallet_name,
wallet_type=wallet_type.value,
shared_wallet_id=shared_wallet_id,
+ onchain_network=onchain_network if wallet_type == WalletType.ONCHAIN else None,
user=user_id,
adminkey=uuid4().hex,
inkey=uuid4().hex,
currency=currency,
)
+ if wallet_type == WalletType.ONCHAIN:
+ wallet.extra.icon = "currency_bitcoin"
if wallet_type == WalletType.FIAT:
wallet.extra.icon = "credit_card"
if settings.ln_address_creation_allowed and wallet.is_lightning_wallet:
@@ -79,6 +99,7 @@ async def delete_wallet(
async def force_delete_wallet(wallet_id: str, conn: Connection | None = None) -> None:
clear_wallet_id_cache(wallet_id)
+
await (conn or db).execute(
"DELETE FROM wallets WHERE id = :wallet",
{"wallet": wallet_id},
@@ -112,15 +133,15 @@ async def delete_unused_wallets(
) -> None:
delta = int(time()) - time_delta
await (conn or db).execute(
- """
+ f"""
DELETE FROM wallets
WHERE (
SELECT COUNT(*) FROM apipayments WHERE wallet_id = wallets.id
) = 0 AND (
- (updated_at is null AND created_at < :delta)
- OR updated_at < :delta
+ (updated_at is null AND created_at < {db.timestamp_placeholder('delta')})
+ OR updated_at < {db.timestamp_placeholder('delta')}
)
- """,
+ """, # noqa: S608
{"delta": delta},
)
@@ -228,7 +249,7 @@ async def get_wallets_paginated(
async def get_wallets_ids(
user_id: str, deleted: bool | None = False, conn: Connection | None = None
) -> list[str]:
- query = """SELECT * FROM wallets WHERE "user" = :user"""
+ query = 'SELECT * FROM wallets WHERE "user" = :user'
if deleted is not None:
query += " AND deleted = :deleted "
wallets = await (conn or db).fetchall(
@@ -350,14 +371,242 @@ async def get_total_balance(conn: Connection | None = None, *, fiat: bool = Fals
"""
SELECT SUM(balance) as balance FROM balances
JOIN wallets ON wallets.id = balances.wallet_id
- WHERE (wallets.wallet_type = 'fiat') = :fiat
+ WHERE wallets.wallet_type = :wallet_type
""",
- {"fiat": fiat},
+ {"wallet_type": "fiat" if fiat else "lightning"},
)
row = result.mappings().first()
return row.get("balance", 0) or 0
+async def init_onchain_wallet_state(
+ wallet: OnchainWallet,
+ encrypted_seed: str | None = None,
+ conn: Connection | None = None,
+) -> OnchainWallet:
+ meta = wallet.onchain_meta.copy()
+ meta.backup_confirmed = False
+ meta.sync_checked_at = 0
+ meta.sync_failed_at = 0
+ meta.sync_error = None
+ meta.sync_checkpoint = None
+ # One conditional write stores setup and recovery material together and
+ # protects against competing setup requests.
+ result = await (conn or db).execute(
+ """UPDATE wallets SET name = :title, onchain_meta = :meta,
+ onchain_network = :network, onchain_wallet_kind = :kind,
+ onchain_address_no = -1,
+ onchain_encrypted_seed = :seed, onchain_sync_lease_until = 0
+ WHERE id = :id AND wallet_type = 'onchain' AND deleted = false
+ AND onchain_wallet_kind IS NULL""",
+ {
+ "id": wallet.id,
+ "title": wallet.name,
+ "meta": meta.json(by_alias=True),
+ "network": wallet.onchain_network,
+ "kind": wallet.onchain_wallet_kind,
+ "seed": encrypted_seed,
+ },
+ )
+ if result.rowcount != 1:
+ existing = await get_onchain_wallet(wallet.id, conn=conn)
+ if existing and existing.onchain_wallet_kind:
+ raise WalletAlreadyConfiguredError()
+ raise ValueError("Onchain wallet is unavailable for setup")
+ configured = await get_onchain_wallet(wallet.id, conn=conn)
+ assert configured
+ return configured
+
+
+async def get_onchain_wallet(
+ wallet_id: str, deleted: bool | None = False, conn: Connection | None = None
+) -> OnchainWallet | None:
+ query = """
+ SELECT *, COALESCE((SELECT balance FROM balances
+ WHERE wallet_id = wallets.id), 0) AS balance_msat
+ FROM wallets WHERE id = :id AND wallet_type = 'onchain'
+ """
+ if deleted is not None:
+ query += " AND deleted = :deleted "
+ return await (conn or db).fetchone(
+ query,
+ {"id": wallet_id, "deleted": deleted},
+ OnchainWallet,
+ )
+
+
+async def get_onchain_encrypted_seed(
+ wallet_id: str, conn: Connection | None = None
+) -> str | None:
+ row: dict = await (conn or db).fetchone(
+ """SELECT onchain_encrypted_seed AS encrypted_seed FROM wallets
+ WHERE id = :wallet AND wallet_type = 'onchain'
+ AND onchain_wallet_kind = 'hot' AND onchain_encrypted_seed IS NOT NULL""",
+ {"wallet": wallet_id},
+ )
+ return row["encrypted_seed"] if row else None
+
+
+async def reserve_onchain_address_index(
+ wallet_id: str,
+ index: int,
+ previous_index: int,
+ conn: Connection | None = None,
+) -> bool:
+ result = await (conn or db).execute(
+ """
+ UPDATE wallets SET onchain_address_no = :index
+ WHERE id = :walet_id AND wallet_type = 'onchain'
+ AND onchain_wallet_kind IS NOT NULL
+ AND onchain_address_no = :previous_index
+ """,
+ {
+ "walet_id": wallet_id,
+ "index": index,
+ "previous_index": previous_index,
+ },
+ )
+ return result.rowcount == 1
+
+
+async def update_onchain_backup_confirmation(
+ wallet: OnchainWallet, conn: Connection | None = None
+) -> OnchainWallet:
+ await (conn or db).execute(
+ """UPDATE wallets SET onchain_meta = :meta
+ WHERE id = :id AND wallet_type = 'onchain'
+ AND onchain_wallet_kind = 'hot'""",
+ {"id": wallet.id, "meta": wallet.onchain_meta.json(by_alias=True)},
+ )
+ updated = await get_onchain_wallet(wallet.id, conn=conn)
+ assert updated
+ return updated
+
+
+async def clear_onchain_wallet_data(
+ wallet_id: str, conn: Connection | None = None
+) -> None:
+ result = await (conn or db).execute(
+ """
+ UPDATE wallets SET onchain_meta = '{}', onchain_config = '{}',
+ onchain_network = NULL, onchain_wallet_kind = NULL,
+ onchain_address_no = -1,
+ onchain_sync_lease_until = 0
+ WHERE id = :id AND wallet_type = 'onchain'
+ AND onchain_wallet_kind = 'watch'
+ AND onchain_encrypted_seed IS NULL
+ """,
+ {"id": wallet_id},
+ )
+ if result.rowcount != 1:
+ raise ValueError("Onchain wallet cannot be removed")
+ await (conn or db).execute(
+ "DELETE FROM onchain_addresses WHERE walet_id = :id",
+ {"id": wallet_id},
+ )
+
+
+async def update_onchain_wallet_config(
+ config: OnchainConfig,
+ wallet_id: str,
+ network: str | None = None,
+ conn: Connection | None = None,
+) -> None:
+ await (conn or db).execute(
+ """UPDATE wallets SET onchain_config = :config,
+ onchain_network = COALESCE(:network, onchain_network, 'Mainnet')
+ WHERE id = :id AND wallet_type = 'onchain'
+ AND (onchain_wallet_kind IS NULL OR CAST(:network AS TEXT) IS NULL
+ OR onchain_network = :network)""",
+ {
+ "id": wallet_id,
+ "config": config.json(exclude={"network"}),
+ "network": network,
+ },
+ )
+
+
+async def acquire_onchain_scan_lease(
+ wallet_id: str,
+ lease: int,
+ now: int,
+ conn: Connection | None = None,
+ *,
+ expected_meta: str | None = None,
+) -> bool:
+ # A conditional scan must not use a freshness decision made before another
+ # scan completed or the wallet was reconfigured.
+ condition = " AND onchain_meta = :meta" if expected_meta is not None else ""
+ values: dict = {"wallet": wallet_id, "lease": lease, "now": now}
+ if expected_meta is not None:
+ values["meta"] = expected_meta
+ acquired = await (conn or db).execute(
+ f"""
+ UPDATE wallets SET onchain_sync_lease_until = :lease
+ WHERE id = :wallet AND onchain_sync_lease_until < :now
+ AND wallet_type = 'onchain' AND deleted = false
+ AND onchain_wallet_kind IS NOT NULL
+ {condition}
+ """, # noqa: S608
+ values,
+ )
+ return acquired.rowcount == 1
+
+
+async def get_onchain_sync_status(
+ wallet_id: str, conn: Connection | None = None
+) -> dict:
+ return (
+ await (conn or db).fetchone(
+ """SELECT onchain_meta, onchain_sync_lease_until FROM wallets
+ WHERE id = :wallet AND wallet_type = 'onchain'""",
+ {"wallet": wallet_id},
+ )
+ or {}
+ )
+
+
+async def get_onchain_wallet_ids(conn: Connection | None = None) -> list[str]:
+ rows: list[dict] = await (conn or db).fetchall("""
+ SELECT id FROM wallets WHERE wallet_type = 'onchain' AND deleted = false
+ AND onchain_wallet_kind IS NOT NULL
+ """)
+ return [row["id"] for row in rows]
+
+
+async def get_onchain_scan_meta(
+ wallet_id: str, lease: int, conn: Connection | None = None
+) -> dict | None:
+ return await (conn or db).fetchone(
+ """SELECT onchain_meta FROM wallets
+ WHERE id = :wallet AND wallet_type = 'onchain'
+ AND onchain_wallet_kind IS NOT NULL
+ AND onchain_sync_lease_until = :lease""",
+ {"wallet": wallet_id, "lease": lease},
+ )
+
+
+async def update_onchain_scan_meta(
+ wallet_id: str,
+ lease: int,
+ meta: dict,
+ conn: Connection | None = None,
+) -> bool:
+ updated = await (conn or db).execute(
+ """UPDATE wallets SET onchain_sync_lease_until = 0,
+ onchain_meta = :meta
+ WHERE id = :wallet AND wallet_type = 'onchain'
+ AND onchain_wallet_kind IS NOT NULL
+ AND onchain_sync_lease_until = :lease""",
+ {
+ "wallet": wallet_id,
+ "lease": lease,
+ "meta": json.dumps(meta),
+ },
+ )
+ return bool(updated.rowcount)
+
+
def clear_wallet_id_cache(wallet_id: str):
cached_wallet: BaseWallet | None = cache.pop(f"auth:wallet:{wallet_id}")
if cached_wallet:
diff --git a/lnbits/core/migrations.py b/lnbits/core/migrations.py
index ea342db..7d65f57 100644
--- a/lnbits/core/migrations.py
+++ b/lnbits/core/migrations.py
@@ -906,3 +906,65 @@ async def m050_add_lightning_address_to_wallets(db: Connection):
async def m051_add_two_factor_to_accounts(db: Connection):
await db.execute("ALTER TABLE accounts ADD COLUMN two_factor TEXT")
+
+
+async def m052_core_onchain_wallets(db: Connection):
+ """Store onchain setup on wallets and blockchain state on their addresses."""
+ for column in (
+ "onchain_network TEXT",
+ "onchain_meta TEXT NOT NULL DEFAULT '{}'",
+ "onchain_config TEXT NOT NULL DEFAULT '{}'",
+ "onchain_wallet_kind TEXT",
+ "onchain_address_no INTEGER NOT NULL DEFAULT -1",
+ "onchain_encrypted_seed TEXT",
+ "onchain_sync_lease_until BIGINT NOT NULL DEFAULT 0",
+ ):
+ await db.execute(f"ALTER TABLE wallets ADD COLUMN {column}")
+ await db.execute(f"""
+ CREATE TABLE onchain_addresses (
+ id TEXT PRIMARY KEY,
+ walet_id TEXT NOT NULL,
+ address TEXT NOT NULL,
+ amount {db.big_int} NOT NULL DEFAULT 0,
+ branch_index INTEGER NOT NULL,
+ address_index INTEGER NOT NULL,
+ note TEXT,
+ has_activity BOOLEAN NOT NULL DEFAULT false,
+ transactions TEXT NOT NULL DEFAULT '[]',
+ utxos TEXT NOT NULL DEFAULT '[]',
+ snapshot_checked_at BIGINT NOT NULL DEFAULT 0,
+ UNIQUE(walet_id, branch_index, address_index)
+ )
+ """)
+
+
+async def m053_balances_view_include_onchain(db: Connection):
+ """Include onchain balances in the shared balances view."""
+ await db.execute("DROP VIEW IF EXISTS balances")
+ await db.execute("""
+ CREATE VIEW balances AS
+ SELECT apipayments.wallet_id,
+ SUM(apipayments.amount - ABS(apipayments.fee)) AS balance
+ FROM wallets
+ LEFT JOIN apipayments ON apipayments.wallet_id = wallets.id
+ WHERE (wallets.deleted = false OR wallets.deleted is NULL)
+ AND wallets.wallet_type != 'onchain'
+ AND (
+ (apipayments.status = 'success' AND apipayments.amount > 0)
+ OR (apipayments.status IN ('success', 'pending') AND apipayments.amount < 0)
+ )
+ GROUP BY apipayments.wallet_id
+
+ UNION ALL
+
+ SELECT wallets.id AS wallet_id, SUM(coins.amount) * 1000 AS balance
+ FROM wallets
+ INNER JOIN (
+ SELECT walet_id, address, MAX(amount) AS amount
+ FROM onchain_addresses
+ GROUP BY walet_id, address
+ ) coins ON coins.walet_id = wallets.id
+ WHERE wallets.wallet_type = 'onchain'
+ AND (wallets.deleted = false OR wallets.deleted is NULL)
+ GROUP BY wallets.id
+ """)
diff --git a/lnbits/core/models/onchain.py b/lnbits/core/models/onchain.py
new file mode 100644
index 0000000..b468ef5
--- /dev/null
+++ b/lnbits/core/models/onchain.py
@@ -0,0 +1,102 @@
+"""Models for onchain addresses and transactions."""
+
+from typing import Literal
+
+from pydantic import BaseModel, Field, validator
+
+
+class Address(BaseModel):
+ id: str
+ address: str
+ walet_id: str
+ amount: int = 0
+ branch_index: int = 0
+ address_index: int
+ note: str | None = None
+ has_activity: bool = False
+
+
+class TransactionInput(BaseModel):
+ tx_id: str
+ vout: int
+ amount: int
+ address: str
+ branch_index: int
+ address_index: int
+ wallet: str
+ tx_hex: str = Field(..., min_length=1, max_length=8000000)
+
+
+class TransactionOutput(BaseModel):
+ amount: int
+ address: str
+ branch_index: int | None = None
+ address_index: int | None = None
+ wallet: str | None = None
+
+
+class MasterPublicKey(BaseModel):
+ id: str
+ public_key: str
+ fingerprint: str
+
+
+class CreatePsbt(BaseModel):
+ masterpubs: list[MasterPublicKey]
+ inputs: list[TransactionInput] = Field(..., min_items=1, max_items=200)
+ outputs: list[TransactionOutput] = Field(..., min_items=1, max_items=100)
+ fee_rate: int
+ tx_size: int
+
+
+class SerializedTransaction(BaseModel):
+ tx_hex: str = Field(..., min_length=1, max_length=8000000)
+ network: Literal["Mainnet", "Testnet", "Testnet4"] | None = None
+
+
+class ExtractPsbt(BaseModel):
+ psbt_base64: str = Field(..., alias="psbtBase64", min_length=1)
+ expected_psbt_base64: str | None = Field(
+ None, alias="expectedPsbtBase64", min_length=1
+ )
+ inputs: list[SerializedTransaction]
+ network: Literal["Mainnet", "Testnet", "Testnet4"] = "Mainnet"
+
+ class Config:
+ allow_population_by_field_name = True
+
+
+class ExtractTx(BaseModel):
+ tx_hex: str = Field(..., min_length=1, max_length=8000000)
+ network: Literal["Mainnet", "Testnet", "Testnet4"] = "Mainnet"
+
+
+class SignedTransaction(BaseModel):
+ tx_hex: str | None
+ tx_json: str | None
+
+
+class HotWalletPayment(BaseModel):
+ transaction: CreatePsbt
+ max_fee_sat: int = Field(..., gt=0, le=10_000_000)
+
+ @validator("transaction", pre=True)
+ @classmethod
+ def whole_satoshis(cls, value):
+ if isinstance(value, dict):
+ for item in value.get("inputs", []) + value.get("outputs", []):
+ if type(item.get("amount")) is not int:
+ raise ValueError("Amounts must be whole satoshis")
+ return value
+
+
+class ScanCheckpoint(BaseModel):
+ height: int = Field(ge=0)
+ block_hash: str = Field(regex=r"^[0-9a-f]{64}$")
+
+
+class Snapshot(BaseModel):
+ address_id: str
+ transactions: list[dict]
+ utxos: list[dict]
+ checked_at: int
diff --git a/lnbits/core/models/wallets.py b/lnbits/core/models/wallets.py
index f7163e0..55ed8d1 100644
--- a/lnbits/core/models/wallets.py
+++ b/lnbits/core/models/wallets.py
@@ -1,12 +1,16 @@
from __future__ import annotations
+import re
from dataclasses import dataclass
from datetime import datetime, timezone
from enum import Enum
+from typing import Literal
+from urllib.parse import urlsplit
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, validator
from lnbits.core.models.lnurl import StoredPayLinks
+from lnbits.core.models.onchain import ScanCheckpoint
from lnbits.db import FilterModel
from lnbits.settings import settings
@@ -22,6 +26,7 @@ class WalletInfo(BaseModel):
class WalletType(Enum):
LIGHTNING = "lightning"
FIAT = "fiat"
+ ONCHAIN = "onchain"
LIGHTNING_SHARED = "lightning-shared"
@@ -128,6 +133,7 @@ class Wallet(BaseWallet):
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
currency: str | None = None
lightning_address: str | None = None
+ onchain_network: Literal["Mainnet", "Testnet", "Testnet4"] | None = None
balance_msat: int = Field(default=0, no_database=True)
extra: WalletExtra = WalletExtra()
stored_paylinks: StoredPayLinks = StoredPayLinks()
@@ -174,6 +180,8 @@ class Wallet(BaseWallet):
return []
def has_permission(self, permission: WalletPermission) -> bool:
+ if self.is_onchain_wallet:
+ return permission == WalletPermission.VIEW_PAYMENTS
if self.wallet_type == WalletType.FIAT.value:
return permission in (
WalletPermission.VIEW_PAYMENTS,
@@ -211,10 +219,14 @@ class Wallet(BaseWallet):
@property
def withdrawable_balance(self) -> int:
- if self.wallet_type == WalletType.FIAT.value:
+ if self.wallet_type in (WalletType.FIAT.value, WalletType.ONCHAIN.value):
return 0
return self.balance_msat - settings.fee_reserve(self.balance_msat)
+ @property
+ def is_onchain_wallet(self) -> bool:
+ return self.wallet_type == WalletType.ONCHAIN.value
+
@property
def is_lightning_wallet(self) -> bool:
return self.wallet_type == WalletType.LIGHTNING.value
@@ -230,6 +242,7 @@ class Wallet(BaseWallet):
class CreateWallet(BaseModel):
+ onchain_network: Literal["Mainnet", "Testnet", "Testnet4"] = "Mainnet"
name: str | None = None
wallet_type: WalletType = WalletType.LIGHTNING
shared_wallet_id: str | None = None
@@ -274,3 +287,98 @@ class WalletsFilters(FilterModel):
name: str | None
currency: str | None
lightning_address: str | None
+
+
+class OnchainMeta(BaseModel):
+ masterpub: str = ""
+ fingerprint: str = ""
+ script_type: str | None = None
+ accountPath: str = "" # noqa: N815 - preserve the stored JSON key
+ xpub: str | None = None
+ backup_confirmed: bool = False
+ sync_checked_at: int = 0
+ sync_failed_at: int = 0
+ sync_error: str | None = None
+ sync_checkpoint: ScanCheckpoint | None = None
+
+
+class OnchainConfig(BaseModel):
+ explorer_provider: Literal["auto", "lnbits", "mempool"] = "auto"
+ mempool_endpoint: str = "https://mempool.space"
+ receive_gap_limit: int = Field(default=20, ge=1, le=1000)
+ change_gap_limit: int = Field(default=5, ge=1, le=1000)
+ sats_denominated: bool = True
+
+ @validator("mempool_endpoint")
+ @classmethod
+ def valid_endpoint(cls, value):
+ url = urlsplit(value)
+ if (
+ url.scheme not in ("https", "http")
+ or not url.hostname
+ or url.username
+ or url.password
+ or url.query
+ or url.fragment
+ ):
+ raise ValueError(
+ "Enter an HTTP(S) explorer URL without credentials or query"
+ )
+ return value.rstrip("/")
+
+
+class OnchainWallet(Wallet):
+ wallet_type: str = WalletType.ONCHAIN.value
+ onchain_meta: OnchainMeta = Field(default_factory=OnchainMeta)
+ onchain_config: OnchainConfig = Field(default_factory=OnchainConfig)
+ onchain_wallet_kind: Literal["watch", "hot"] | None = None
+ onchain_address_no: int = -1
+
+
+class CreateOnchainWalletMeta(BaseModel):
+ accountPath: str = "" # noqa: N815 - preserve the API field name
+ xpub: str | None = None
+
+
+class CreateOnchainWallet(BaseModel):
+ masterpub: str = Field(..., min_length=1, max_length=10000)
+ title: str = Field(..., min_length=1, max_length=100)
+ network: Literal["Mainnet", "Testnet", "Testnet4"] = "Mainnet"
+ meta: CreateOnchainWalletMeta = Field(default_factory=CreateOnchainWalletMeta)
+
+
+class OnchainWalletConfigResponse(OnchainConfig):
+ network: Literal["Mainnet", "Testnet", "Testnet4"] = "Mainnet"
+ lnbits_explorer_network: str | None = None
+ explorer_url: str
+
+
+class NewHotWallet(BaseModel):
+ title: str = Field(..., min_length=1, max_length=100)
+ network: Literal["Mainnet", "Testnet", "Testnet4"] = "Mainnet"
+ script_type: Literal["p2pkh", "p2sh", "p2wpkh", "p2tr"] = "p2wpkh"
+ account_path: str | None = Field(None, min_length=1, max_length=3037)
+
+ @validator("account_path")
+ @classmethod
+ def valid_account_path(cls, value: str | None) -> str | None:
+ if value is None:
+ return None
+ path = value.strip().replace("h", "'").replace("H", "'")
+ if not re.fullmatch(r"m(?:/[0-9]{1,10}'?)+", path):
+ raise ValueError("Enter a BIP32 account path, such as m/84'/0'/0'")
+ parts = path.split("/")[1:]
+ # Leave two levels for the receiving/change branch and address index.
+ if len(parts) > 253 or any(int(p.rstrip("'")) >= 2**31 for p in parts):
+ raise ValueError("Derivation path depth or index is out of range")
+ if not path.endswith("'"):
+ raise ValueError(
+ "The account path must end in a hardened index. "
+ "Do not include receiving/change branches or address indexes."
+ )
+ return "m/" + "/".join(
+ str(int(p.rstrip("'"))) + ("'" if p.endswith("'") else "") for p in parts
+ )
+
+ class Config:
+ extra = "forbid"
diff --git a/lnbits/core/services/blockexplorer.py b/lnbits/core/services/blockexplorer.py
index 7233dcf..878bd01 100644
--- a/lnbits/core/services/blockexplorer.py
+++ b/lnbits/core/services/blockexplorer.py
@@ -1,5 +1,13 @@
import asyncio
+import math
+import re
+import httpx
+from embit.transaction import Transaction as EmbitTransaction
+from starlette.concurrency import run_in_threadpool
+
+from lnbits.core.models.onchain import ScanCheckpoint
+from lnbits.core.models.wallets import OnchainConfig
from lnbits.settings import settings
from lnbits.task_manager import OnchainAddressEvent
from lnbits.utils.electrum import (
@@ -19,12 +27,323 @@ from lnbits.utils.electrum import (
scripthash_from_address,
)
+TXID = re.compile(r"^[0-9a-f]{64}$")
+NETWORKS = {"main": "Mainnet", "test": "Testnet", "test4": "Testnet4"}
+_WALLET_TXID = re.compile(r"^[0-9a-f]{64}$")
-def _client() -> ElectrumClient:
- return ElectrumClient(
- settings.lnbits_blockexplorer_electrum_url,
- network=network_from_name(settings.lnbits_blockexplorer_network),
- )
+
+class BlockExplorerWalletSession:
+ """One explorer connection for complete wallet scans and payment operations."""
+
+ def __init__(self) -> None:
+ self.client = _client()
+ self.transactions: dict[str, EmbitTransaction] = {}
+ self.details: dict[str, dict] = {}
+ self.blocks: dict[int, dict] = {}
+
+ async def __aenter__(self):
+ await self.client.__aenter__()
+ return self
+
+ async def __aexit__(self, *args):
+ await self.client.__aexit__(*args)
+
+ async def raw_transaction(self, txid: str) -> str:
+ return await self.client.get_transaction(txid)
+
+ async def checkpoint(self) -> ScanCheckpoint:
+ tip = await self.client.get_tip()
+ block = parse_block_header(tip.hex, tip.height)
+ return ScanCheckpoint(height=tip.height, block_hash=block.hash)
+
+ async def block_hash(self, height: int) -> str:
+ # Bypass the session cache when checking for reorganisations.
+ header = await self.client.get_block_header(height)
+ if not isinstance(header, str):
+ raise ValueError("Invalid block header")
+ return parse_block_header(header, height).hash
+
+ async def _transaction(self, txid: str) -> EmbitTransaction:
+ if not _WALLET_TXID.fullmatch(txid):
+ raise ValueError("Invalid transaction ID")
+ if txid not in self.transactions:
+ raw = await self.raw_transaction(txid)
+ if len(raw) > 8_000_000:
+ raise ValueError("Transaction too large")
+ tx = await run_in_threadpool(EmbitTransaction.parse, bytes.fromhex(raw))
+ if tx.txid().hex() != txid:
+ raise ValueError("Transaction ID mismatch")
+ if len(self.transactions) >= 10000:
+ self.transactions.clear()
+ self.transactions[txid] = tx
+ return self.transactions[txid]
+
+ def _outputs(self, tx: EmbitTransaction) -> list[dict]:
+ outputs = []
+ for output in tx.vout:
+ try:
+ address = output.script_pubkey.address(self.client.network)
+ except ValueError:
+ address = None
+ outputs.append(
+ {
+ "value": output.value,
+ "scriptpubkey": output.script_pubkey.data.hex(),
+ "scriptpubkey_address": address,
+ }
+ )
+ return outputs
+
+ async def _status(self, height: int) -> dict:
+ if height <= 0:
+ return {"confirmed": False}
+ if height not in self.blocks:
+ header = await self.client.get_block_header(height)
+ if not isinstance(header, str):
+ raise ValueError("Invalid block header")
+ block = parse_block_header(header, height)
+ self.blocks[height] = {
+ "confirmed": True,
+ "block_height": height,
+ "block_time": block.timestamp,
+ "block_hash": block.hash,
+ }
+ return self.blocks[height].copy()
+
+ async def history(
+ self,
+ address: str,
+ *,
+ previous: list[dict] | None = None,
+ checkpoint: ScanCheckpoint | None = None,
+ ) -> list[dict]:
+ history = await self.client.get_history(scripthash_from_address(address))
+ if len(history) > 25000:
+ raise ValueError("Explorer history limit reached")
+ if len(self.details) >= 10000:
+ self.details.clear()
+ self.details.update({tx["txid"]: tx for tx in previous or []})
+ transactions = []
+ for entry in history:
+ cached = self.details.get(entry.tx_hash)
+ if cached is not None:
+ status = cached["status"]
+ if not (
+ checkpoint
+ and status["confirmed"]
+ and status["block_height"] == entry.height
+ and 0 < entry.height <= checkpoint.height
+ ):
+ status = await self._status(entry.height)
+ transactions.append({**cached, "status": status})
+ self.details[entry.tx_hash] = transactions[-1]
+ continue
+ tx = await self._transaction(entry.tx_hash)
+ vin = []
+ for inp in tx.vin:
+ coinbase = inp.txid == bytes(32) and inp.vout == 0xFFFFFFFF
+ prevout = None
+ if not coinbase:
+ parent = self.details.get(inp.txid.hex())
+ outputs = (
+ parent["vout"]
+ if parent is not None
+ else self._outputs(await self._transaction(inp.txid.hex()))
+ )
+ prevout = outputs[inp.vout]
+ vin.append(
+ {
+ "txid": inp.txid.hex(),
+ "vout": inp.vout,
+ "prevout": prevout,
+ "is_coinbase": coinbase,
+ "sequence": inp.sequence,
+ }
+ )
+ vout = self._outputs(tx)
+ fee = (
+ 0
+ if any(i["is_coinbase"] for i in vin)
+ else (
+ sum(i["prevout"]["value"] for i in vin)
+ - sum(o["value"] for o in vout)
+ )
+ )
+ if fee < 0:
+ raise ValueError("Invalid transaction fee")
+ transactions.append(
+ {
+ "txid": entry.tx_hash,
+ "vin": vin,
+ "vout": vout,
+ "fee": fee,
+ "status": await self._status(entry.height),
+ }
+ )
+ self.details[entry.tx_hash] = transactions[-1]
+ return transactions
+
+ async def utxos(self, address: str) -> list[dict]:
+ coins = await self.client.listunspent(scripthash_from_address(address))
+ return [
+ {
+ "txid": coin.tx_hash,
+ "vout": coin.tx_pos,
+ "value": coin.value,
+ "status": await self._status(coin.height),
+ }
+ for coin in coins
+ ]
+
+ async def fees(self) -> dict:
+ rates = await asyncio.gather(
+ *(self.client.estimate_fee(blocks) for blocks in (1, 3, 6, 144))
+ )
+ # Electrum returns BTC/kB; the send form expects integer sat/vB.
+ fees = [max(1, math.ceil(rate * 100000)) if rate > 0 else 1 for rate in rates]
+ fees = [max(fees[i:]) for i in range(len(fees))]
+ return dict(
+ zip(
+ ("fastestFee", "halfHourFee", "hourFee", "economyFee"),
+ fees,
+ strict=True,
+ ),
+ minimumFee=1,
+ )
+
+ async def broadcast(self, raw: str) -> str:
+ return await self.client.broadcast(raw)
+
+
+class MempoolExplorer:
+ def __init__(
+ self,
+ config: OnchainConfig,
+ network: str,
+ client: httpx.AsyncClient | None = None,
+ ):
+ self.client = client or httpx.AsyncClient(
+ base_url=mempool_url(config, network) + "/",
+ timeout=15,
+ follow_redirects=False,
+ trust_env=False,
+ )
+
+ async def __aenter__(self):
+ await self.client.__aenter__()
+ return self
+
+ async def __aexit__(self, *args):
+ await self.client.__aexit__(*args)
+
+ async def checkpoint(self) -> ScanCheckpoint:
+ response = await self.client.get("api/blocks/tip/height")
+ response.raise_for_status()
+ height = int(response.text)
+ return ScanCheckpoint(height=height, block_hash=await self.block_hash(height))
+
+ async def block_hash(self, height: int) -> str:
+ response = await self.client.get(f"api/block-height/{height}")
+ response.raise_for_status()
+ block_hash = response.text.strip()
+ if not TXID.fullmatch(block_hash):
+ raise ValueError("Invalid block hash")
+ return block_hash
+
+ async def history(
+ self,
+ address: str,
+ *,
+ previous: list[dict] | None = None,
+ checkpoint: ScanCheckpoint | None = None,
+ ) -> list[dict]:
+ cached = {
+ tx["txid"]: tx
+ for tx in previous or []
+ if checkpoint
+ and tx["status"]["confirmed"]
+ and tx["status"]["block_height"] <= checkpoint.height
+ }
+ response = await self.client.get(f"api/address/{address}/txs")
+ response.raise_for_status()
+ page = response.json()
+ result: dict[str, dict] = {}
+ seen: set[str] = set()
+ mempool_full = False
+ for _ in range(1000):
+ if not isinstance(page, list):
+ raise ValueError("Invalid explorer response")
+ for tx in page:
+ if not TXID.fullmatch(tx["txid"]):
+ raise ValueError("Invalid transaction ID")
+ result[tx["txid"]] = tx
+ confirmed = [tx for tx in page if tx["status"]["confirmed"]]
+ mempool_full = mempool_full or len(page) - len(confirmed) >= 50
+ if any(
+ tx["txid"] in cached and tx["status"] == cached[tx["txid"]]["status"]
+ for tx in confirmed
+ ):
+ # Only confirmed history covered by the verified checkpoint is
+ # retained. Pending or newer entries must come from this scan.
+ for txid, tx in cached.items():
+ result.setdefault(txid, tx)
+ break
+ if len(confirmed) < 25:
+ break
+ last = confirmed[-1]["txid"]
+ if last in seen or not TXID.fullmatch(last):
+ raise ValueError("Invalid explorer pagination")
+ seen.add(last)
+ response = await self.client.get(f"api/address/{address}/txs/chain/{last}")
+ response.raise_for_status()
+ page = response.json()
+ else:
+ raise ValueError("Explorer history limit reached")
+ # The address endpoint caps pending transactions at 50. Absence from a
+ # full page does not mean a previously seen transaction was dropped.
+ if mempool_full:
+ await self._check_missing_pending(previous or [], result)
+ return list(result.values())
+
+ async def _check_missing_pending(self, previous: list[dict], result: dict) -> None:
+ for tx in previous:
+ if tx["txid"] in result:
+ continue
+ response = await self.client.get(f"api/tx/{tx['txid']}/status")
+ if response.status_code == 404:
+ continue
+ response.raise_for_status()
+ result[tx["txid"]] = {**tx, "status": response.json()}
+
+ async def utxos(self, address: str) -> list[dict]:
+ response = await self.client.get(f"api/address/{address}/utxo")
+ response.raise_for_status()
+ return response.json()
+
+ async def fees(self) -> dict:
+ response = await self.client.get("api/v1/fees/recommended")
+ response.raise_for_status()
+ return response.json()
+
+ async def raw_transaction(self, txid: str) -> str:
+ response = await self.client.get(f"api/tx/{txid}/hex")
+ response.raise_for_status()
+ return response.text.strip()
+
+ async def broadcast(self, raw: str) -> str:
+ response = await self.client.post("api/tx", content=raw)
+ response.raise_for_status()
+ return response.text.strip()
+
+
+class LnbitsExplorer(BlockExplorerWalletSession):
+ def __init__(self, network: str):
+ if local_explorer_network() != network:
+ raise ValueError("LNbits block explorer is unavailable for this network")
+ super().__init__()
+
+
+Explorer = MempoolExplorer | LnbitsExplorer
async def fetch_recent_blocks(count: int = 5) -> list[BlockInfo]:
@@ -123,3 +442,46 @@ def address_event_to_response(event: OnchainAddressEvent) -> AddressResponse:
history=event.history,
history_error=event.history_error,
)
+
+
+def local_explorer_network() -> str | None:
+ if not settings.lnbits_blockexplorer_enabled:
+ return None
+ return NETWORKS.get(settings.lnbits_blockexplorer_network)
+
+
+def provider_name(config: OnchainConfig, network: str) -> str:
+ if config.explorer_provider == "auto":
+ return "lnbits" if local_explorer_network() == network else "mempool"
+ return config.explorer_provider
+
+
+def mempool_url(config: OnchainConfig, network: str) -> str:
+ endpoint = config.mempool_endpoint.rstrip("/")
+ # The standard host serves multiple chains; custom URLs identify one chain.
+ if endpoint == "https://mempool.space":
+ endpoint += {"Mainnet": "", "Testnet": "/testnet", "Testnet4": "/testnet4"}[
+ network
+ ]
+ return endpoint
+
+
+def explorer_url(config: OnchainConfig, network: str) -> str:
+ return (
+ "/blockexplorer"
+ if provider_name(config, network) == "lnbits"
+ else mempool_url(config, network)
+ )
+
+
+def explorer_client(config: OnchainConfig, network: str) -> Explorer:
+ if provider_name(config, network) == "lnbits":
+ return LnbitsExplorer(network)
+ return MempoolExplorer(config, network)
+
+
+def _client() -> ElectrumClient:
+ return ElectrumClient(
+ settings.lnbits_blockexplorer_electrum_url,
+ network=network_from_name(settings.lnbits_blockexplorer_network),
+ )
diff --git a/lnbits/core/services/onchain.py b/lnbits/core/services/onchain.py
new file mode 100644
index 0000000..e9ad159
--- /dev/null
+++ b/lnbits/core/services/onchain.py
@@ -0,0 +1,677 @@
+"""Onchain wallet key management, signing, and synchronization.
+
+Private material is kept outside the settings database. The database pins its
+fingerprint so a lost key cannot silently be replaced when restoring an instance.
+"""
+
+import asyncio
+import base64
+import hashlib
+import json
+import os
+import secrets
+import tempfile
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+from time import monotonic
+
+from loguru import logger
+from pydantic import BaseModel
+from starlette.concurrency import run_in_threadpool
+
+from lnbits.core.crud.onchain import (
+ create_fresh_addresses,
+ get_address_at_index,
+ get_address_snapshot,
+ get_addresses,
+ get_last_used_address_index,
+ get_wallet_snapshots,
+ update_address_snapshot,
+)
+from lnbits.core.crud.settings import get_settings_field, set_settings_field
+from lnbits.core.crud.wallets import (
+ acquire_onchain_scan_lease,
+ get_onchain_scan_meta,
+ get_onchain_sync_status,
+ get_onchain_wallet,
+ get_onchain_wallet_ids,
+ reserve_onchain_address_index,
+ update_onchain_scan_meta,
+)
+from lnbits.core.models.onchain import (
+ Address,
+ HotWalletPayment,
+ MasterPublicKey,
+ ScanCheckpoint,
+ SignedTransaction,
+ Snapshot,
+)
+from lnbits.core.models.wallets import OnchainMeta, OnchainWallet
+from lnbits.core.services.blockexplorer import TXID, Explorer, explorer_client
+from lnbits.core.services.wallets import get_wallet_addresses
+from lnbits.db import Connection
+from lnbits.settings import settings
+from lnbits.task_manager import task_manager
+from lnbits.utils.onchain import (
+ address_script,
+ create_psbt,
+ decrypt_mnemonic,
+ encrypt_mnemonic,
+ finalize_signed_psbt,
+ psbt_fee,
+ root_key,
+ script_address,
+ transaction_details,
+ wallet_descriptor,
+ wally,
+)
+
+KEY_RECORD = "onchain_key"
+SCAN_SLOTS = asyncio.Semaphore(4)
+SCAN_MAX_AGE = 120
+SCAN_RETRY_DELAY = 60
+
+
+class OnchainKeyStatus(BaseModel):
+ configured: bool = False
+ backup_confirmed: bool = False
+ fingerprint: str | None = None
+ source: str | None = None
+ error: str | None = None
+
+
+def key_path() -> Path:
+ return Path(settings.lnbits_data_folder) / ".onchain_key"
+
+
+def decode_key(encoded: str) -> bytes:
+ try:
+ key = base64.b64decode(encoded.strip(), validate=True)
+ if len(key) != 32:
+ raise ValueError
+ return key
+ except (ValueError, TypeError) as exc:
+ raise ValueError(
+ "The onchain encryption key must contain 32 random bytes."
+ ) from exc
+
+
+def key_fingerprint(key: bytes) -> str:
+ return hashlib.sha256(key).hexdigest()
+
+
+def read_onchain_key() -> bytes:
+ configured = settings.lnbits_onchain_master_key
+ # Compatibility with Watchonly installations configured before core integration.
+ encoded = (
+ configured.get_secret_value()
+ if configured
+ else os.getenv("WATCHONLY_MASTER_KEY")
+ )
+ try:
+ stored = decode_key(key_path().read_text()) if key_path().exists() else None
+ except OSError as exc:
+ raise ValueError("Cannot read the onchain encryption key file.") from exc
+ if encoded:
+ key = decode_key(encoded)
+ if stored is not None and key != stored:
+ raise ValueError(
+ "The environment key does not match the saved onchain key."
+ )
+ return key
+ if stored is None:
+ raise ValueError(
+ "Restore the onchain encryption key or complete setup in Payments settings."
+ )
+ return stored
+
+
+async def onchain_key_status() -> OnchainKeyStatus:
+ record = await get_settings_field(KEY_RECORD)
+ pinned = (record.value or {}) if record else {}
+ status = OnchainKeyStatus(fingerprint=pinned.get("fingerprint"))
+ try:
+ key = await run_in_threadpool(read_onchain_key)
+ fingerprint = key_fingerprint(key)
+ if status.fingerprint and fingerprint != status.fingerprint:
+ raise ValueError(
+ "The onchain encryption key does not match this database. "
+ "Restore its original key."
+ )
+ status.fingerprint = fingerprint
+ status.configured = True
+ status.backup_confirmed = bool(pinned.get("backup_confirmed"))
+ status.source = (
+ "environment"
+ if settings.lnbits_onchain_master_key or os.getenv("WATCHONLY_MASTER_KEY")
+ else "file"
+ )
+ except ValueError as exc:
+ status.error = str(exc)
+ return status
+
+
+async def setup_onchain_key(restore: str | None = None) -> OnchainKeyStatus:
+ record = await get_settings_field(KEY_RECORD)
+ pinned = (record.value or {}) if record else {}
+ if restore is not None:
+ key = decode_key(restore)
+ if record and pinned.get("fingerprint") != key_fingerprint(key):
+ raise ValueError("This recovery key does not match the database.")
+ # An operator-managed environment key must agree with a restored file.
+ configured = settings.lnbits_onchain_master_key
+ encoded = (
+ configured.get_secret_value()
+ if configured
+ else os.getenv("WATCHONLY_MASTER_KEY")
+ )
+ if encoded and decode_key(encoded) != key:
+ raise ValueError(
+ "This recovery key does not match the configured environment key."
+ )
+ await run_in_threadpool(_save_key, key)
+ else:
+ try:
+ key = await run_in_threadpool(read_onchain_key)
+ except ValueError:
+ if (
+ record
+ or key_path().exists()
+ or settings.lnbits_onchain_master_key
+ or os.getenv("WATCHONLY_MASTER_KEY")
+ ):
+ raise ValueError(
+ "Restore the original onchain key before continuing."
+ ) from None
+ key = secrets.token_bytes(32)
+ await run_in_threadpool(_save_key, key)
+ fingerprint = key_fingerprint(key)
+ if record and pinned.get("fingerprint") != fingerprint:
+ raise ValueError("The onchain encryption key does not match this database.")
+ if not record:
+ await set_settings_field(
+ KEY_RECORD, {"fingerprint": fingerprint, "backup_confirmed": False}
+ )
+ return await onchain_key_status()
+
+
+async def confirm_onchain_key_backup(fingerprint: str) -> OnchainKeyStatus:
+ status = await setup_onchain_key()
+ if not status.configured or status.fingerprint != fingerprint:
+ raise ValueError(
+ "The backup does not match the current onchain encryption key."
+ )
+ await set_settings_field(
+ KEY_RECORD, {"fingerprint": fingerprint, "backup_confirmed": True}
+ )
+ return await onchain_key_status()
+
+
+async def require_onchain_payments() -> None:
+ if not settings.lnbits_allow_onchain_payments:
+ raise ValueError("Server onchain payments are disabled in Payments settings.")
+ status = await onchain_key_status()
+ if not status.configured or not status.backup_confirmed:
+ raise ValueError(
+ "The administrator must set up and back up the onchain "
+ "encryption key in Payments settings."
+ )
+
+
+def encrypt_wallet_mnemonic(mnemonic: str, wallet: OnchainWallet) -> str:
+ return encrypt_mnemonic(mnemonic, read_onchain_key(), _mnemonic_context(wallet))
+
+
+def decrypt_wallet_mnemonic(encrypted: str, wallet: OnchainWallet) -> str:
+ return decrypt_mnemonic(encrypted, read_onchain_key(), _mnemonic_context(wallet))
+
+
+def sign_payment( # noqa: C901
+ wallet: OnchainWallet, encrypted: str, payment: HotWalletPayment
+) -> SignedTransaction:
+ data = payment.transaction.copy(deep=True)
+ if not wallet.onchain_network:
+ raise ValueError("Onchain wallet network is not configured")
+ if not wallet.onchain_meta.backup_confirmed:
+ raise ValueError("Back up this wallet before sending")
+ if not 1 <= len(data.inputs) <= 200 or not 1 <= len(data.outputs) <= 100:
+ raise ValueError("Invalid number of transaction inputs or outputs")
+ seen = set()
+ for inp in data.inputs:
+ if inp.wallet != wallet.id:
+ raise ValueError("Every input must belong to the selected wallet")
+ if inp.branch_index not in (0, 1) or not 0 <= inp.address_index < 2**31:
+ raise ValueError("Invalid input derivation")
+ if (inp.tx_id, inp.vout) in seen:
+ raise ValueError("Duplicate transaction input")
+ seen.add((inp.tx_id, inp.vout))
+ if not 0 < inp.amount <= 2_100_000_000_000_000:
+ raise ValueError("Invalid input amount")
+ network = (
+ wally.WALLY_NETWORK_BITCOIN_MAINNET
+ if wallet.onchain_network == "Mainnet"
+ else wally.WALLY_NETWORK_BITCOIN_TESTNET
+ )
+ for out in data.outputs:
+ if not 546 <= out.amount <= 2_100_000_000_000_000:
+ raise ValueError("Output is below the minimum or exceeds the supply")
+ if (
+ script_address(address_script(out.address), network).lower()
+ != out.address.lower()
+ ):
+ raise ValueError("Recipient is on a different network")
+ if out.wallet is not None and (
+ out.wallet != wallet.id
+ or out.branch_index != 1
+ or out.address_index is None
+ or not 0 <= out.address_index < 2**31
+ ):
+ raise ValueError("Invalid change output")
+ # Never trust public keys supplied by the client to select a private key.
+ data.masterpubs = [
+ MasterPublicKey(
+ id=wallet.id,
+ public_key=wallet.onchain_meta.masterpub,
+ fingerprint=wallet.onchain_meta.fingerprint,
+ )
+ ]
+ psbt = create_psbt(data)
+ fee = psbt_fee(psbt)
+ if not 0 < fee <= payment.max_fee_sat:
+ raise ValueError("Transaction fee exceeds the approved maximum")
+ mnemonic = decrypt_wallet_mnemonic(encrypted, wallet)
+ if (
+ wallet_descriptor(
+ mnemonic,
+ wallet.onchain_network,
+ wallet.onchain_meta.script_type or "p2wpkh",
+ wallet.onchain_meta.accountPath or None,
+ )[0]
+ != wallet.onchain_meta.masterpub
+ ):
+ raise ValueError("Wallet key does not match its descriptor")
+ wally.psbt_sign_bip32(psbt, root_key(mnemonic, wallet.onchain_network), 0)
+ transaction = finalize_signed_psbt(psbt)
+ details = transaction_details(transaction, network)
+ details["fee"] = fee
+ return SignedTransaction(
+ tx_hex=wally.tx_to_hex(transaction, wally.WALLY_TX_FLAG_USE_WITNESS),
+ tx_json=json.dumps(details),
+ )
+
+
+async def scan_address(
+ client: Explorer, address: Address, checkpoint: ScanCheckpoint | None = None
+) -> None:
+ previous = await get_address_snapshot(address.id)
+ transactions = await client.history(
+ address.address,
+ previous=previous.transactions if previous else None,
+ checkpoint=checkpoint,
+ )
+ utxos = await client.utxos(address.address)
+ if not isinstance(utxos, list):
+ raise ValueError("Invalid UTXOs")
+ outpoints = set()
+ amount = 0
+ for coin in utxos:
+ point = (coin["txid"], coin["vout"])
+ if (
+ not TXID.fullmatch(coin["txid"])
+ or type(coin["vout"]) is not int
+ or coin["vout"] < 0
+ or type(coin["value"]) is not int
+ or not 0 <= coin["value"] <= 2_100_000_000_000_000
+ or point in outpoints
+ ):
+ raise ValueError("Invalid UTXO")
+ outpoints.add(point)
+ amount += coin["value"]
+ if amount > 2_100_000_000_000_000:
+ raise ValueError("Invalid balance")
+ first_seen = (
+ {tx["txid"]: tx.get("first_seen") for tx in previous.transactions}
+ if previous
+ else {}
+ )
+ now = int(time.time())
+ for tx in transactions:
+ tx["first_seen"] = first_seen.get(tx["txid"]) or now
+ await update_address_snapshot(
+ Snapshot(
+ address_id=address.id,
+ transactions=transactions,
+ utxos=utxos,
+ checked_at=now,
+ ),
+ amount,
+ )
+
+
+def scan_skip_reason(
+ status: dict, now: float, max_age: int = SCAN_MAX_AGE
+) -> str | None:
+ if status.get("onchain_sync_lease_until", 0) > now:
+ return "another scan holds the wallet lease"
+ meta = OnchainMeta.parse_raw(status.get("onchain_meta", "{}"))
+ if meta.sync_error:
+ if now - meta.sync_failed_at < SCAN_RETRY_DELAY:
+ return f"retry cooldown is active ({SCAN_RETRY_DELAY}s)"
+ elif meta.sync_checked_at and now - meta.sync_checked_at <= max_age:
+ return f"last successful scan is within {max_age}s"
+ return None
+
+
+def scan_due(status: dict, now: float, max_age: int = SCAN_MAX_AGE) -> bool:
+ return scan_skip_reason(status, now, max_age) is None
+
+
+async def is_scan_due(wallet_id: str) -> bool:
+ return scan_due(await get_onchain_sync_status(wallet_id), int(time.time()))
+
+
+async def scan_wallet(wallet_id: str, *, max_age: int | None = None) -> None:
+ async with SCAN_SLOTS:
+ await _scan_with_lease(wallet_id, max_age=max_age)
+
+
+def request_scan(wallet_id: str, *, if_needed: bool = False) -> bool:
+ name = f"onchain-sync-{wallet_id}"
+ existing = task_manager.get_task(name)
+ if existing and not existing.task.done():
+ logger.info(
+ f"Skipping onchain scan request for wallet {wallet_id}: "
+ "scan already queued or running."
+ )
+ return False
+ if if_needed:
+ logger.info(f"Requesting onchain scan if needed for wallet {wallet_id}.")
+ # A queued conditional check must not swallow a later explicit refresh.
+ # Both tasks still share the database lease once they begin scanning.
+ name += "-if-needed"
+ existing = task_manager.get_task(name)
+ if existing and not existing.task.done():
+ logger.info(
+ f"Skipping conditional onchain scan request for wallet {wallet_id}: "
+ "check already queued or running."
+ )
+ return False
+ task_manager.create_task(
+ scan_wallet(wallet_id, max_age=SCAN_MAX_AGE if if_needed else None), name=name
+ )
+ return True
+
+
+async def sync_wallets() -> None:
+ # Bound provider load. API-triggered scans share the database lease.
+ for wallet_id in await get_onchain_wallet_ids():
+ await scan_wallet(wallet_id, max_age=0)
+
+
+async def get_fresh_address(
+ wallet_id: str, conn: Connection | None = None
+) -> Address | None:
+ wallet = await get_onchain_wallet(wallet_id, conn=conn)
+ if not wallet or not wallet.onchain_wallet_kind:
+ return None
+
+ last_used = await get_last_used_address_index(wallet_id, conn=conn)
+ index = max(wallet.onchain_address_no, last_used) + 1
+ if not await reserve_onchain_address_index(
+ wallet_id, index, wallet.onchain_address_no, conn=conn
+ ):
+ raise ValueError("Another process changed the wallet")
+
+ address = await get_address_at_index(wallet_id, 0, index, conn=conn)
+ if not address:
+ await create_fresh_addresses(wallet_id, index, index + 1, conn=conn)
+ address = await get_address_at_index(wallet_id, 0, index, conn=conn)
+
+ return address
+
+
+async def get_wallet_state(wallet_id: str) -> dict:
+ wallet = await get_onchain_wallet(wallet_id)
+ addresses = (
+ await get_addresses(wallet.id) if wallet and wallet.onchain_wallet_kind else []
+ )
+ snapshots = await get_wallet_snapshots(wallet_id)
+ status = await get_onchain_sync_status(wallet_id)
+ meta = OnchainMeta.parse_raw(status.get("onchain_meta", "{}"))
+ balances: dict[str, int] = {}
+ for address in addresses:
+ balances[address.address] = max(
+ balances.get(address.address, 0), address.amount
+ )
+ return {
+ "addresses": addresses,
+ "snapshots": snapshots,
+ "scanning": status.get("onchain_sync_lease_until", 0) > time.time(),
+ "sync_due": bool(wallet and wallet.onchain_wallet_kind)
+ and scan_due(status, int(time.time())),
+ "checked_at": meta.sync_checked_at,
+ "error": meta.sync_error,
+ "balance_sat": sum(balances.values()),
+ }
+
+
+async def get_onchain_daily_stats(wallet_id: str) -> list[dict]:
+ state = await get_wallet_state(wallet_id)
+ own = {a.address for a in state["addresses"]}
+ transactions = {
+ tx["txid"]: tx
+ for snapshot in state["snapshots"]
+ for tx in snapshot.transactions
+ }
+ days: dict[str, dict] = {}
+ for tx in transactions.values():
+ if not tx["status"]["confirmed"]:
+ continue
+ date = (
+ datetime.fromtimestamp(tx["status"]["block_time"], timezone.utc)
+ .date()
+ .isoformat()
+ )
+ row = days.setdefault(
+ date,
+ {
+ "date": date,
+ "balance_in": 0,
+ "balance_out": 0,
+ "count_in": 0,
+ "count_out": 0,
+ "fee": 0,
+ },
+ )
+ incoming = sum(
+ o["value"] for o in tx["vout"] if o.get("scriptpubkey_address") in own
+ )
+ outgoing = sum(
+ i["prevout"]["value"]
+ for i in tx["vin"]
+ if (i.get("prevout") or {}).get("scriptpubkey_address") in own
+ )
+ net = incoming - outgoing
+ if net >= 0:
+ row["balance_in"] += net
+ row["count_in"] += 1
+ else:
+ row["balance_out"] += -net
+ row["count_out"] += 1
+ row["fee"] += tx.get("fee", 0)
+ balance = 0
+ result = []
+ for date in sorted(days):
+ row = days[date]
+ balance += row["balance_in"] - row["balance_out"]
+ row["balance"] = balance
+ result.append(row)
+ return result
+
+
+def _save_key(key: bytes) -> None:
+ """Publish a complete mode-0600 file without ever replacing an existing key."""
+ target = key_path()
+ target.parent.mkdir(parents=True, exist_ok=True)
+ fd, temporary = tempfile.mkstemp(prefix=".onchain-key-", dir=target.parent)
+ try:
+ with os.fdopen(fd, "w") as file:
+ file.write(base64.b64encode(key).decode() + "\n")
+ file.flush()
+ os.fsync(file.fileno())
+ try:
+ os.link(temporary, target)
+ except FileExistsError:
+ if decode_key(target.read_text()) != key:
+ raise ValueError(
+ "An onchain key already exists. It cannot be replaced."
+ ) from None
+ if os.name == "posix":
+ directory = os.open(target.parent, os.O_RDONLY)
+ try:
+ os.fsync(directory)
+ finally:
+ os.close(directory)
+ finally:
+ Path(temporary).unlink(missing_ok=True)
+
+
+def _mnemonic_context(wallet: OnchainWallet) -> bytes:
+ # Keep the original context: account ID and wallet ID were the same ID.
+ return json.dumps(
+ [
+ "onchain-v1",
+ wallet.id,
+ wallet.id,
+ wallet.onchain_network,
+ wallet.onchain_meta.masterpub,
+ ],
+ separators=(",", ":"),
+ ).encode()
+
+
+async def _scan(wallet_id: str) -> ScanCheckpoint | str:
+ wallet = await get_onchain_wallet(wallet_id)
+ if not wallet or not wallet.onchain_wallet_kind:
+ return "Wallet was removed or is no longer configured."
+ async with explorer_client(
+ wallet.onchain_config, wallet.onchain_network or "Mainnet"
+ ) as client:
+ tip = await client.checkpoint()
+ checkpoint = wallet.onchain_meta.sync_checkpoint
+ # A failed scan may have written only part of a reorganised history.
+ if checkpoint and (
+ wallet.onchain_meta.sync_error
+ or checkpoint.height > tip.height
+ or await client.block_hash(checkpoint.height) != checkpoint.block_hash
+ ):
+ checkpoint = None
+ checked = set()
+ for _ in range(1000):
+ addresses = await get_wallet_addresses(wallet)
+ current = await get_onchain_wallet(wallet_id)
+ if (
+ not current
+ or not current.onchain_wallet_kind
+ or current.onchain_meta.masterpub != wallet.onchain_meta.masterpub
+ or current.onchain_network != wallet.onchain_network
+ ):
+ return "Wallet was removed or reconfigured during the scan."
+ pending = [a for a in addresses if a.id not in checked]
+ if not pending:
+ break
+ for address in pending:
+ await scan_address(client, address, checkpoint)
+ checked.add(address.id)
+ else:
+ raise ValueError("Address discovery limit reached")
+ if await client.block_hash(tip.height) != tip.block_hash:
+ raise ValueError("Blockchain changed during scan")
+ return tip
+
+
+async def _finish_scan(
+ wallet_id: str,
+ lease: int,
+ error: str | None,
+ conn: Connection | None = None,
+ *,
+ checkpoint: ScanCheckpoint | None = None,
+) -> bool:
+ now = int(time.time())
+ state: dict = {"sync_error": error, "sync_failed_at": now if error else 0}
+ if error is None:
+ state["sync_checked_at"] = now
+ if checkpoint is not None:
+ state["sync_checkpoint"] = checkpoint.dict()
+ row = await get_onchain_scan_meta(wallet_id, lease, conn)
+ if not row:
+ return False
+ meta = json.loads(row["onchain_meta"])
+ meta.update(state)
+ return await update_onchain_scan_meta(wallet_id, lease, meta, conn)
+
+
+async def _scan_with_lease(wallet_id: str, *, max_age: int | None = None) -> None:
+ now = int(time.time())
+ lease = now + 1800
+ expected_meta = None
+ if max_age is not None:
+ status = await get_onchain_sync_status(wallet_id)
+ reason = scan_skip_reason(status, now, max_age)
+ if reason:
+ logger.info(f"Onchain scan skipped for wallet {wallet_id}: {reason}.")
+ return
+ expected_meta = status.get("onchain_meta")
+ if not await acquire_onchain_scan_lease(
+ wallet_id, lease, now, expected_meta=expected_meta
+ ):
+ logger.info(
+ f"Onchain scan skipped for wallet {wallet_id}: "
+ "scan lease was not acquired (wallet state changed or lease unavailable)."
+ )
+ return
+ started = monotonic()
+ logger.info(f"Onchain scan started for wallet {wallet_id}.")
+ error = None
+ checkpoint = None
+ outcome = "success"
+ reason = ""
+ try:
+ result = await asyncio.wait_for(_scan(wallet_id), timeout=1500)
+ if isinstance(result, str):
+ error = result
+ outcome = "aborted"
+ reason = error
+ else:
+ checkpoint = result
+ except asyncio.CancelledError:
+ outcome = "cancelled"
+ error = "Update interrupted. Retry to refresh the blockchain snapshot."
+ raise
+ except Exception as exc:
+ outcome = "failed"
+ reason = type(exc).__name__
+ # Never return credentials, explorer URLs, raw responses or stack traces.
+ error = "Blockchain update failed. Previous balances and history are retained."
+ finally:
+ try:
+ saved = await _finish_scan(wallet_id, lease, error, checkpoint=checkpoint)
+ if not saved and outcome == "success":
+ outcome = "aborted"
+ reason = "wallet or scan lease changed before status could be saved"
+ except asyncio.CancelledError:
+ outcome = "cancelled"
+ reason = "interrupted while saving scan status"
+ raise
+ except Exception as exc:
+ outcome = "failed"
+ reason = f"could not save scan status ({type(exc).__name__})"
+ raise
+ finally:
+ detail = f", reason={reason.rstrip('.')}" if reason else ""
+ logger.info(
+ f"Onchain scan ended for wallet {wallet_id}: "
+ f"outcome={outcome}, duration={monotonic() - started:.2f}s{detail}."
+ )
diff --git a/lnbits/core/services/payments.py b/lnbits/core/services/payments.py
index 3a784e6..c606dba 100644
--- a/lnbits/core/services/payments.py
+++ b/lnbits/core/services/payments.py
@@ -532,6 +532,8 @@ async def update_wallet_balance(
memo: str | None = None,
conn: Connection | None = None,
):
+ if wallet.is_onchain_wallet:
+ raise ValueError("Onchain balances are determined by the blockchain.")
if amount == 0:
raise ValueError("Amount cannot be 0.")
diff --git a/lnbits/core/services/wallets.py b/lnbits/core/services/wallets.py
index 2b78720..18f9f30 100644
--- a/lnbits/core/services/wallets.py
+++ b/lnbits/core/services/wallets.py
@@ -1,3 +1,6 @@
+from starlette.concurrency import run_in_threadpool
+
+from lnbits.core.crud.onchain import create_fresh_addresses, get_addresses
from lnbits.core.crud.users import (
get_account,
get_account_by_username_or_email,
@@ -9,11 +12,16 @@ from lnbits.core.crud.wallets import (
get_standalone_wallet,
get_wallet,
get_wallets,
+ init_onchain_wallet_state,
update_wallet,
)
from lnbits.core.models.misc import SimpleStatus
+from lnbits.core.models.onchain import Address
from lnbits.core.models.users import Account
from lnbits.core.models.wallets import (
+ CreateOnchainWallet,
+ OnchainMeta,
+ OnchainWallet,
Wallet,
WalletSharePermission,
WalletShareStatus,
@@ -21,6 +29,11 @@ from lnbits.core.models.wallets import (
)
from lnbits.db import Connection
from lnbits.helpers import sha256s
+from lnbits.utils.onchain import (
+ descriptor_fingerprint,
+ descriptor_type,
+ parse_key,
+)
async def invite_to_wallet(
@@ -170,6 +183,70 @@ async def create_lightning_shared_wallet(
)
+async def init_onchain_wallet(
+ data: CreateOnchainWallet, wallet: OnchainWallet
+) -> OnchainWallet | None:
+ descriptor, network = await run_in_threadpool(parse_key, data.masterpub)
+ assert network
+ signing_network = "Testnet" if data.network == "Testnet4" else data.network
+ if signing_network != network["name"]:
+ raise ValueError(
+ "Account network error. This account is for '{}'".format(network["name"])
+ )
+
+ wallet.name = data.title
+ wallet.onchain_network = data.network
+ wallet.onchain_wallet_kind = "watch"
+ wallet.onchain_meta = OnchainMeta(
+ accountPath=data.meta.accountPath,
+ xpub=data.meta.xpub,
+ masterpub=data.masterpub,
+ fingerprint=descriptor_fingerprint(descriptor),
+ script_type=descriptor_type(descriptor),
+ )
+
+ return await init_onchain_wallet_state(wallet)
+
+
+async def get_wallet_addresses(wallet: OnchainWallet) -> list[Address]:
+ addresses = await get_addresses(wallet.id)
+ config = wallet.onchain_config
+
+ if not addresses:
+ await create_fresh_addresses(wallet.id, 0, config.receive_gap_limit)
+ await create_fresh_addresses(wallet.id, 0, config.change_gap_limit, True)
+ addresses = await get_addresses(wallet.id)
+
+ receive_addresses = list(filter(lambda addr: addr.branch_index == 0, addresses))
+ change_addresses = list(filter(lambda addr: addr.branch_index == 1, addresses))
+
+ last_receive_address = list(
+ filter(lambda addr: addr.has_activity, receive_addresses)
+ )[-1:]
+ last_change_address = list(
+ filter(lambda addr: addr.has_activity, change_addresses)
+ )[-1:]
+
+ if last_receive_address:
+ current_index = receive_addresses[-1].address_index
+ address_index = last_receive_address[0].address_index
+ await create_fresh_addresses(
+ wallet.id, current_index + 1, address_index + config.receive_gap_limit + 1
+ )
+
+ if last_change_address:
+ current_index = change_addresses[-1].address_index
+ address_index = last_change_address[0].address_index
+ await create_fresh_addresses(
+ wallet.id,
+ current_index + 1,
+ address_index + config.change_gap_limit + 1,
+ True,
+ )
+
+ return await get_addresses(wallet.id)
+
+
async def _accept_invitation_to_shared_wallet(
invited_user: Account,
source_wallet: Wallet,
diff --git a/lnbits/core/views/admin_api.py b/lnbits/core/views/admin_api.py
index 988f713..c0b673f 100644
--- a/lnbits/core/views/admin_api.py
+++ b/lnbits/core/views/admin_api.py
@@ -1,15 +1,19 @@
+import base64
+import json
import os
import time
from http import HTTPStatus
from pathlib import Path
from shutil import make_archive
from subprocess import Popen
-from typing import cast
+from typing import Annotated, cast
-from fastapi import APIRouter, Depends, File, HTTPException
+from fastapi import APIRouter, Depends, File, Header, HTTPException, Response
from fastapi.responses import FileResponse
+from pydantic import SecretStr
from sqlalchemy.engine import URL, make_url
from sqlalchemy.exc import ArgumentError
+from starlette.concurrency import run_in_threadpool
from lnbits.core.models.notifications import NotificationType
from lnbits.core.models.users import AccessTokenPayload, Account
@@ -19,6 +23,13 @@ from lnbits.core.services import (
update_cached_settings,
)
from lnbits.core.services.notifications import send_email_notification
+from lnbits.core.services.onchain import (
+ OnchainKeyStatus,
+ confirm_onchain_key_backup,
+ onchain_key_status,
+ read_onchain_key,
+ setup_onchain_key,
+)
from lnbits.core.services.settings import dict_to_settings
from lnbits.core.services.two_factor import (
sync_two_factor_policy,
@@ -99,6 +110,23 @@ async def api_update_settings(
payload: AccessTokenPayload = Depends(access_token_payload),
):
policy_changed = await validate_two_factor_policy(data, account.id, payload)
+ if "lnbits_allow_onchain_payments" in data.__fields_set__:
+ enabled = data.lnbits_allow_onchain_payments
+ if (
+ enabled != settings.lnbits_allow_onchain_payments
+ and not account.is_super_user
+ ):
+ raise HTTPException(
+ HTTPStatus.FORBIDDEN, "Only the super user can change onchain payments."
+ )
+ if enabled:
+ status = await onchain_key_status()
+ if not status.configured or not status.backup_confirmed:
+ raise HTTPException(
+ HTTPStatus.CONFLICT,
+ "Set up and back up the onchain encryption key "
+ "before enabling onchain payments.",
+ )
enqueue_admin_notification(
NotificationType.settings_update, {"username": account.username}
)
@@ -121,6 +149,78 @@ async def api_update_settings(
return {"status": "Success"}
+@admin_router.get("/api/v1/onchain/key", dependencies=[Depends(check_super_user)])
+async def api_onchain_key_status(response: Response) -> OnchainKeyStatus:
+ response.headers["Cache-Control"] = "no-store"
+ return await onchain_key_status()
+
+
+@admin_router.post("/api/v1/onchain/key", dependencies=[Depends(check_super_user)])
+async def api_setup_onchain_key(
+ response: Response,
+ recovery_key: Annotated[
+ SecretStr | None, Header(alias="X-Onchain-Recovery-Key")
+ ] = None,
+) -> OnchainKeyStatus:
+ response.headers["Cache-Control"] = "no-store"
+ try:
+ return await setup_onchain_key(
+ recovery_key.get_secret_value() if recovery_key else None
+ )
+ except (ValueError, OSError) as exc:
+ raise HTTPException(
+ HTTPStatus.CONFLICT,
+ "Cannot set up the onchain key. Check the recovery key, "
+ "existing configuration and data-folder permissions.",
+ ) from exc
+
+
+@admin_router.post(
+ "/api/v1/onchain/key/backup", dependencies=[Depends(check_super_user)]
+)
+async def api_backup_onchain_key() -> Response:
+ try:
+ status = await setup_onchain_key()
+ key = await run_in_threadpool(read_onchain_key)
+ except (ValueError, OSError) as exc:
+ raise HTTPException(
+ HTTPStatus.CONFLICT,
+ "The onchain key is unavailable. Restore its original backup.",
+ ) from exc
+ return Response(
+ content=json.dumps(
+ {
+ "version": 1,
+ "key": base64.b64encode(key).decode(),
+ "fingerprint": status.fingerprint,
+ },
+ indent=2,
+ ),
+ media_type="application/json",
+ headers={
+ "Cache-Control": "no-store",
+ "Pragma": "no-cache",
+ "Content-Disposition": 'attachment; filename="lnbits-onchain-key.json"',
+ },
+ )
+
+
+@admin_router.post(
+ "/api/v1/onchain/key/confirm", dependencies=[Depends(check_super_user)]
+)
+async def api_confirm_onchain_key_backup(
+ fingerprint: Annotated[str, Header(alias="X-Onchain-Key-Fingerprint")],
+ response: Response,
+) -> OnchainKeyStatus:
+ response.headers["Cache-Control"] = "no-store"
+ try:
+ return await confirm_onchain_key_backup(fingerprint)
+ except (ValueError, OSError) as exc:
+ raise HTTPException(
+ HTTPStatus.CONFLICT, "The backup does not match the onchain key."
+ ) from exc
+
+
@admin_router.patch(
"/api/v1/settings",
status_code=HTTPStatus.OK,
@@ -202,7 +302,10 @@ async def api_download_backup() -> FileResponse:
make_archive(last_filename, "zip", settings.lnbits_data_folder)
return FileResponse(
- path=f"{last_filename}.zip", filename=filename, media_type="application/zip"
+ path=f"{last_filename}.zip",
+ filename=filename,
+ media_type="application/zip",
+ headers={"Cache-Control": "no-store"},
)
diff --git a/lnbits/core/views/onchain_api.py b/lnbits/core/views/onchain_api.py
new file mode 100644
index 0000000..58611c7
--- /dev/null
+++ b/lnbits/core/views/onchain_api.py
@@ -0,0 +1,477 @@
+import json
+import re
+from http import HTTPStatus
+from typing import Annotated
+
+from fastapi import APIRouter, Depends, Header, HTTPException, Request, Response
+from pydantic import SecretStr
+from starlette.concurrency import run_in_threadpool
+
+from lnbits.core.crud.onchain import get_address_by_id, update_address
+from lnbits.core.crud.wallets import (
+ WalletAlreadyConfiguredError,
+ get_onchain_encrypted_seed,
+ get_onchain_wallet,
+ init_onchain_wallet_state,
+ update_onchain_backup_confirmation,
+)
+from lnbits.core.models.onchain import (
+ Address,
+ CreatePsbt,
+ ExtractPsbt,
+ ExtractTx,
+ HotWalletPayment,
+ SerializedTransaction,
+ SignedTransaction,
+)
+from lnbits.core.models.wallets import NewHotWallet, OnchainMeta, OnchainWallet
+from lnbits.core.services.blockexplorer import TXID, explorer_client
+from lnbits.core.services.onchain import (
+ decrypt_wallet_mnemonic,
+ encrypt_wallet_mnemonic,
+ get_fresh_address,
+ get_onchain_daily_stats,
+ get_wallet_state,
+ is_scan_due,
+ read_onchain_key,
+ request_scan,
+ require_onchain_payments,
+ sign_payment,
+)
+from lnbits.core.services.wallets import get_wallet_addresses
+from lnbits.decorators import (
+ OnchainAuth,
+ require_onchain_admin,
+ require_onchain_read,
+)
+from lnbits.settings import settings
+from lnbits.utils.onchain import (
+ address_script,
+ combine_matching_psbt,
+ create_psbt,
+ descriptor_fingerprint,
+ finalize_signed_psbt,
+ new_mnemonic,
+ parse_key,
+ psbt_fee,
+ set_previous_transaction,
+ transaction_details,
+ wallet_descriptor,
+ wally,
+)
+
+onchain_router = APIRouter(prefix="/api/v1/onchain", tags=["Onchain"])
+
+
+#############################ADDRESSES##########################
+
+
+@onchain_router.get("/address/{wallet_id}")
+async def api_fresh_address(
+ wallet_id: str,
+ auth: OnchainAuth = Depends(require_onchain_read),
+) -> Address:
+ wallet = await get_onchain_wallet(wallet_id)
+ if not wallet or wallet_id != auth.wallet_id or not wallet.onchain_wallet_kind:
+ raise HTTPException(HTTPStatus.NOT_FOUND, "Wallet does not exist.")
+ if wallet.onchain_wallet_kind == "hot" and not wallet.onchain_meta.backup_confirmed:
+ raise HTTPException(HTTPStatus.CONFLICT, "Back up this wallet before receiving")
+ address = await get_fresh_address(wallet_id)
+ assert address
+ return address
+
+
+@onchain_router.put("/address/{address_id}")
+async def api_update_address(
+ address_id: str,
+ req: Request,
+ auth: OnchainAuth = Depends(require_onchain_admin),
+):
+ address = await get_address_by_id(address_id)
+ if not address or address.walet_id != auth.wallet_id:
+ raise HTTPException(
+ status_code=HTTPStatus.NOT_FOUND, detail="Address does not exist."
+ )
+
+ wallet = await get_onchain_wallet(address.walet_id)
+ if not wallet or not wallet.onchain_wallet_kind:
+ raise HTTPException(HTTPStatus.NOT_FOUND, "Wallet does not exist.")
+
+ body = await req.json()
+ if "amount" in body:
+ raise HTTPException(400, "Balances are updated only by the blockchain scanner")
+ if "note" in body:
+ if not isinstance(body["note"], str) or len(body["note"]) > 500:
+ raise HTTPException(400, "Address note must be at most 500 characters")
+ address.note = body["note"]
+ address = await update_address(address)
+ return address
+
+
+@onchain_router.get("/addresses/{wallet_id}")
+async def api_get_addresses(
+ wallet_id: str,
+ auth: OnchainAuth = Depends(require_onchain_read),
+) -> list[Address]:
+ if wallet_id != auth.wallet_id:
+ raise HTTPException(HTTPStatus.NOT_FOUND, "Wallet does not exist.")
+ wallet = await get_onchain_wallet(wallet_id)
+ if not wallet or not wallet.onchain_wallet_kind:
+ raise HTTPException(HTTPStatus.NOT_FOUND, "Wallet does not exist.")
+ return await get_wallet_addresses(wallet)
+
+
+@onchain_router.post("/psbt")
+async def api_psbt_create(
+ data: CreatePsbt,
+ _auth: OnchainAuth = Depends(require_onchain_admin),
+):
+ try:
+ return await run_in_threadpool(
+ lambda: wally.psbt_to_base64(create_psbt(data), 0)
+ )
+
+ except Exception as exc:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST, detail=str(exc)
+ ) from exc
+
+
+@onchain_router.put("/psbt/utxos")
+async def api_psbt_utxos_tx(
+ req: Request,
+ _auth: OnchainAuth = Depends(require_onchain_admin),
+):
+ """Extract previous unspent transaction outputs (tx_id, vout) from PSBT"""
+
+ body = await req.json()
+ try:
+ psbt = wally.psbt_from_base64(body["psbtBase64"], 0)
+ res = []
+ for index in range(wally.psbt_get_num_inputs(psbt)):
+ res.append(
+ {
+ "tx_id": bytes(wally.psbt_get_input_previous_txid(psbt, index))[
+ ::-1
+ ].hex(),
+ "vout": wally.psbt_get_input_output_index(psbt, index),
+ }
+ )
+
+ return res
+ except Exception as exc:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST, detail=str(exc)
+ ) from exc
+
+
+@onchain_router.put("/psbt/extract")
+async def api_psbt_extract_tx(
+ data: ExtractPsbt,
+ _auth: OnchainAuth = Depends(require_onchain_admin),
+) -> SignedTransaction:
+ return await run_in_threadpool(_extract_psbt, data)
+
+
+@onchain_router.put("/tx/extract")
+async def api_extract_tx(
+ data: ExtractTx,
+ _auth: OnchainAuth = Depends(require_onchain_admin),
+):
+ return await run_in_threadpool(_extract_transaction, data)
+
+
+@onchain_router.post("/tx")
+async def api_tx_broadcast(
+ data: SerializedTransaction,
+ auth: OnchainAuth = Depends(require_onchain_admin),
+):
+ if settings.lnbits_only_allow_incoming_payments:
+ raise HTTPException(403, "Only incoming payments allowed")
+ wallet = await get_onchain_wallet(auth.wallet_id)
+ if not wallet:
+ raise HTTPException(HTTPStatus.NOT_FOUND, "Wallet does not exist.")
+ if data.network and (wallet.onchain_network or "Mainnet") != data.network:
+ raise HTTPException(400, "Bitcoin network does not match this LNbits wallet")
+ try:
+ async with explorer_client(
+ wallet.onchain_config, wallet.onchain_network or "Mainnet"
+ ) as client:
+ tx_id = await client.broadcast(data.tx_hex)
+ if not TXID.fullmatch(tx_id):
+ raise ValueError("Invalid broadcast response")
+ request_scan(auth.wallet_id)
+ return tx_id
+ except Exception as exc:
+ raise HTTPException(
+ 400, "Broadcast failed. Check the transaction status before retrying."
+ ) from exc
+
+
+@onchain_router.get("/hot-wallet/status")
+async def hot_wallet_status(
+ _auth: OnchainAuth = Depends(require_onchain_admin),
+):
+ try:
+ await require_onchain_payments()
+ read_onchain_key()
+ return {"available": True}
+ except ValueError:
+ return {"available": False}
+
+
+@onchain_router.post(
+ "/hot-wallet",
+ response_model=OnchainWallet,
+ response_model_exclude={"adminkey", "inkey"},
+)
+async def create_hot_wallet(
+ data: NewHotWallet,
+ response: Response,
+ recovery_phrase: Annotated[
+ SecretStr | None, Header(alias="X-Onchain-Recovery-Phrase")
+ ] = None,
+ auth: OnchainAuth = Depends(require_onchain_admin),
+):
+ no_store(response)
+ wallet = await get_onchain_wallet(auth.wallet_id)
+ if not wallet:
+ raise HTTPException(HTTPStatus.NOT_FOUND, "Wallet does not exist.")
+ if (wallet.onchain_network or "Mainnet") != data.network:
+ raise HTTPException(400, "Bitcoin network does not match this LNbits wallet")
+ try:
+ await require_onchain_payments()
+ read_onchain_key()
+ except ValueError as exc:
+ raise HTTPException(HTTPStatus.SERVICE_UNAVAILABLE, str(exc)) from exc
+ try:
+ mnemonic = await run_in_threadpool(
+ new_mnemonic,
+ recovery_phrase.get_secret_value() if recovery_phrase else None,
+ )
+ descriptor, path = await run_in_threadpool(
+ wallet_descriptor,
+ mnemonic,
+ data.network,
+ data.script_type,
+ data.account_path,
+ )
+ except ValueError as exc:
+ raise HTTPException(HTTPStatus.BAD_REQUEST, "Invalid recovery phrase") from exc
+ if not data.title.strip():
+ raise HTTPException(HTTPStatus.BAD_REQUEST, "Enter a wallet name")
+ wallet.name = data.title.strip()
+ wallet.onchain_network = data.network
+ wallet.onchain_wallet_kind = "hot"
+ wallet.onchain_meta = OnchainMeta(
+ masterpub=descriptor,
+ fingerprint=descriptor_fingerprint(parse_key(descriptor)[0]),
+ script_type=data.script_type,
+ accountPath=path,
+ )
+ encrypted = encrypt_wallet_mnemonic(mnemonic, wallet)
+ try:
+ wallet = await init_onchain_wallet_state(wallet, encrypted_seed=encrypted)
+ except WalletAlreadyConfiguredError as exc:
+ raise HTTPException(HTTPStatus.CONFLICT, str(exc)) from exc
+ except ValueError as exc:
+ raise HTTPException(HTTPStatus.BAD_REQUEST, str(exc)) from exc
+ if not wallet or not wallet.onchain_wallet_kind:
+ raise HTTPException(HTTPStatus.NOT_FOUND, "Wallet does not exist.")
+ await get_wallet_addresses(wallet)
+ request_scan(auth.wallet_id)
+ return wallet
+
+
+@onchain_router.post("/hot-wallet/{wallet_id}/backup")
+async def backup_hot_wallet(
+ wallet_id: str,
+ response: Response,
+ auth: OnchainAuth = Depends(require_onchain_admin),
+):
+ no_store(response)
+ wallet = await get_onchain_wallet(wallet_id)
+ if not wallet or wallet_id != auth.wallet_id or not wallet.onchain_wallet_kind:
+ raise HTTPException(HTTPStatus.NOT_FOUND, "Wallet does not exist.")
+ encrypted = await secret_for_wallet(wallet)
+ try:
+ mnemonic = await run_in_threadpool(decrypt_wallet_mnemonic, encrypted, wallet)
+ return {"mnemonic": mnemonic, "path": wallet.onchain_meta.accountPath}
+ except ValueError as exc:
+ raise HTTPException(
+ HTTPStatus.SERVICE_UNAVAILABLE, "Wallet key cannot be unlocked"
+ ) from exc
+
+
+@onchain_router.post(
+ "/hot-wallet/{wallet_id}/backup/confirm",
+ response_model=OnchainWallet,
+ response_model_exclude={"adminkey", "inkey"},
+)
+async def confirm_backup(
+ wallet_id: str,
+ auth: OnchainAuth = Depends(require_onchain_admin),
+):
+ wallet = await get_onchain_wallet(wallet_id)
+ if not wallet or wallet_id != auth.wallet_id or not wallet.onchain_wallet_kind:
+ raise HTTPException(HTTPStatus.NOT_FOUND, "Wallet does not exist.")
+ await secret_for_wallet(wallet)
+ wallet.onchain_meta.backup_confirmed = True
+ return await update_onchain_backup_confirmation(wallet)
+
+
+@onchain_router.post("/hot-wallet/{wallet_id}/sign")
+async def sign_hot_wallet_payment(
+ wallet_id: str,
+ data: HotWalletPayment,
+ response: Response,
+ auth: OnchainAuth = Depends(require_onchain_admin),
+):
+ no_store(response)
+ if settings.lnbits_only_allow_incoming_payments:
+ raise HTTPException(403, "Only incoming payments allowed")
+ try:
+ await require_onchain_payments()
+ except ValueError as exc:
+ raise HTTPException(HTTPStatus.SERVICE_UNAVAILABLE, str(exc)) from exc
+ wallet = await get_onchain_wallet(wallet_id)
+ if not wallet or wallet_id != auth.wallet_id or not wallet.onchain_wallet_kind:
+ raise HTTPException(HTTPStatus.NOT_FOUND, "Wallet does not exist.")
+ encrypted = await secret_for_wallet(wallet)
+ try:
+ # Reject spent/stale inputs before asking the signer to use the seed.
+ async with explorer_client(
+ wallet.onchain_config, wallet.onchain_network or "Mainnet"
+ ) as client:
+ for address in {i.address for i in data.transaction.inputs}:
+ address_script(address)
+ utxos = await client.utxos(address)
+ available = {(u["txid"], u["vout"], u["value"]) for u in utxos}
+ if any(
+ (i.tx_id, i.vout, i.amount) not in available
+ for i in data.transaction.inputs
+ if i.address == address
+ ):
+ raise ValueError("Inputs have changed")
+ return await run_in_threadpool(sign_payment, wallet, encrypted, data)
+ except Exception as exc:
+ # Native library/encryption errors must not disclose key material.
+ raise HTTPException(
+ HTTPStatus.BAD_REQUEST,
+ "Cannot sign: check wallet backup, recipients, inputs, network and fee. "
+ "If these are correct, ask the administrator to check "
+ "the wallet encryption key.",
+ ) from exc
+
+
+@onchain_router.post("/sync", status_code=202)
+async def start_sync(
+ if_needed: bool = False, auth: OnchainAuth = Depends(require_onchain_admin)
+):
+ if if_needed and not await is_scan_due(auth.wallet_id):
+ return {"scheduled": False}
+ return {"scheduled": request_scan(auth.wallet_id, if_needed=if_needed)}
+
+
+@onchain_router.get("/state")
+async def wallet_state(auth: OnchainAuth = Depends(require_onchain_read)):
+ return await get_wallet_state(auth.wallet_id)
+
+
+@onchain_router.get("/stats/daily")
+async def daily_stats(auth: OnchainAuth = Depends(require_onchain_read)):
+ return await get_onchain_daily_stats(auth.wallet_id)
+
+
+@onchain_router.get("/fees")
+async def fee_estimates(auth: OnchainAuth = Depends(require_onchain_read)):
+ wallet = await get_onchain_wallet(auth.wallet_id)
+ if not wallet:
+ raise HTTPException(404, "Onchain wallet not found")
+ try:
+ async with explorer_client(
+ wallet.onchain_config, wallet.onchain_network or "Mainnet"
+ ) as client:
+ return await client.fees()
+ except Exception as exc:
+ raise HTTPException(503, "Fee estimates are unavailable") from exc
+
+
+@onchain_router.get("/tx/{tx_id}/hex")
+async def previous_transaction(
+ tx_id: str, auth: OnchainAuth = Depends(require_onchain_read)
+):
+ if not TXID.fullmatch(tx_id):
+ raise HTTPException(400, "Invalid transaction ID")
+ wallet = await get_onchain_wallet(auth.wallet_id)
+ if not wallet:
+ raise HTTPException(404, "Onchain wallet not found")
+ try:
+ async with explorer_client(
+ wallet.onchain_config, wallet.onchain_network or "Mainnet"
+ ) as client:
+ raw = await client.raw_transaction(tx_id)
+ if len(raw) > 8_000_000 or not re.fullmatch(r"[0-9a-fA-F]+", raw):
+ raise ValueError("Invalid transaction")
+ return raw
+ except Exception as exc:
+ raise HTTPException(503, "Previous transaction is unavailable") from exc
+
+
+def _extract_psbt(data: ExtractPsbt) -> SignedTransaction:
+ network = (
+ wally.WALLY_NETWORK_BITCOIN_MAINNET
+ if data.network == "Mainnet"
+ else wally.WALLY_NETWORK_BITCOIN_TESTNET
+ )
+ try:
+ psbt = wally.psbt_from_base64(data.psbt_base64, 0)
+ if data.expected_psbt_base64:
+ expected = wally.psbt_from_base64(data.expected_psbt_base64, 0)
+ psbt = combine_matching_psbt(expected, psbt)
+ for i, inp in enumerate(data.inputs):
+ set_previous_transaction(psbt, i, inp.tx_hex)
+
+ fee = psbt_fee(psbt)
+ transaction = finalize_signed_psbt(psbt)
+ tx_hex = wally.tx_to_hex(transaction, wally.WALLY_TX_FLAG_USE_WITNESS)
+ tx = transaction_details(transaction, network)
+ tx["fee"] = fee
+ signed_tx = SignedTransaction(tx_hex=tx_hex, tx_json=json.dumps(tx))
+ return signed_tx
+ except Exception as exc:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST, detail=str(exc)
+ ) from exc
+
+
+def _extract_transaction(data: ExtractTx):
+ network = (
+ wally.WALLY_NETWORK_BITCOIN_MAINNET
+ if data.network == "Mainnet"
+ else wally.WALLY_NETWORK_BITCOIN_TESTNET
+ )
+ try:
+ transaction = wally.tx_from_hex(data.tx_hex, wally.WALLY_TX_FLAG_USE_WITNESS)
+ tx = transaction_details(transaction, network)
+ return {"tx_json": tx}
+ except Exception as exc:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST, detail=str(exc)
+ ) from exc
+
+
+def no_store(response: Response):
+ response.headers["Cache-Control"] = "no-store"
+ response.headers["Pragma"] = "no-cache"
+
+
+async def secret_for_wallet(wallet: OnchainWallet) -> str:
+ if wallet.onchain_wallet_kind != "hot":
+ raise HTTPException(
+ HTTPStatus.BAD_REQUEST, "This wallet uses an external signer"
+ )
+ encrypted_seed = await get_onchain_encrypted_seed(wallet.id)
+ if encrypted_seed is None:
+ raise HTTPException(HTTPStatus.CONFLICT, "Wallet key is unavailable")
+ return encrypted_seed
diff --git a/lnbits/core/views/wallet_api.py b/lnbits/core/views/wallet_api.py
index 57981a3..d49b9cd 100644
--- a/lnbits/core/views/wallet_api.py
+++ b/lnbits/core/views/wallet_api.py
@@ -1,4 +1,5 @@
from http import HTTPStatus
+from typing import Literal
from uuid import uuid4
from fastapi import (
@@ -6,38 +7,58 @@ from fastapi import (
Body,
Depends,
HTTPException,
+ Query,
)
from lnbits.core.crud.wallets import (
+ WalletAlreadyConfiguredError,
+ clear_onchain_wallet_data,
clear_wallet_cache,
create_wallet,
+ get_onchain_wallet,
get_wallets_paginated,
+ update_onchain_wallet_config,
)
from lnbits.core.models import CreateWallet, KeyType, Wallet, WalletTypeInfo
from lnbits.core.models.lnurl import StoredPayLink, StoredPayLinks
from lnbits.core.models.misc import SimpleStatus
from lnbits.core.models.users import Account, AccountId
from lnbits.core.models.wallets import (
+ CreateOnchainWallet,
+ OnchainConfig,
+ OnchainWallet,
+ OnchainWalletConfigResponse,
WalletsFilters,
WalletSharePermission,
WalletType,
)
+from lnbits.core.services.blockexplorer import (
+ explorer_url,
+ local_explorer_network,
+ provider_name,
+)
from lnbits.core.services.lightning_address import set_wallet_lightning_address
+from lnbits.core.services.onchain import request_scan
from lnbits.core.services.wallets import (
create_lightning_shared_wallet,
delete_wallet_share,
+ get_wallet_addresses,
+ init_onchain_wallet,
invite_to_wallet,
reject_wallet_invitation,
update_wallet_share_permissions,
)
from lnbits.db import Filters, Page
from lnbits.decorators import (
+ OnchainAuth,
check_account_exists,
check_account_id_exists,
check_api_write_access,
parse_filters,
require_admin_key,
require_invoice_key,
+ require_onchain_admin,
+ require_onchain_read,
)
from lnbits.helpers import generate_filter_params_openapi
from lnbits.settings import settings
@@ -181,6 +202,8 @@ async def api_update_wallet(
wallet.extra.pinned = pinned if pinned is not None else wallet.extra.pinned
wallet.currency = currency if currency is not None else wallet.currency
+ if lightning_address and wallet.is_onchain_wallet:
+ raise HTTPException(400, "Onchain wallets use Bitcoin receive addresses")
if lightning_address and lightning_address != wallet.lightning_address:
if not settings.lnbits_allow_custom_wallet_lightning_addresses:
raise HTTPException(
@@ -247,4 +270,115 @@ async def api_create_wallet(
wallet_name=data.name,
wallet_type=data.wallet_type,
currency=data.currency,
+ onchain_network=data.onchain_network,
+ )
+
+
+@wallet_router.get("/onchain", response_model_exclude={"adminkey", "inkey"})
+async def api_wallets_retrieve(
+ network: Literal["Mainnet", "Testnet", "Testnet4"] | None = Query(None),
+ auth: OnchainAuth = Depends(require_onchain_read),
+) -> OnchainWallet | None:
+ wallet = await get_onchain_wallet(auth.wallet_id)
+ if not wallet or not wallet.onchain_wallet_kind:
+ return None
+ if network and wallet.onchain_network != network:
+ return None
+ return wallet
+
+
+@wallet_router.post("/onchain", response_model_exclude={"adminkey", "inkey"})
+async def api_wallet_create_or_update(
+ data: CreateOnchainWallet,
+ auth: OnchainAuth = Depends(require_onchain_admin),
+) -> OnchainWallet:
+ wallet = await get_onchain_wallet(auth.wallet_id)
+ if not wallet:
+ raise HTTPException(HTTPStatus.NOT_FOUND, "Wallet does not exist.")
+ if (wallet.onchain_network or "Mainnet") != data.network:
+ raise HTTPException(400, "Bitcoin network does not match this LNbits wallet")
+ try:
+ wallet = await init_onchain_wallet(data, wallet)
+ except WalletAlreadyConfiguredError as exc:
+ raise HTTPException(HTTPStatus.CONFLICT, str(exc)) from exc
+ except Exception as exc:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST, detail=str(exc)
+ ) from exc
+ if not wallet or not wallet.onchain_wallet_kind:
+ raise HTTPException(HTTPStatus.NOT_FOUND, "Wallet does not exist.")
+ await get_wallet_addresses(wallet)
+ request_scan(auth.wallet_id)
+ return wallet
+
+
+@wallet_router.delete("/onchain/{wallet_id}")
+async def api_wallet_delete(
+ wallet_id: str,
+ auth: OnchainAuth = Depends(require_onchain_admin),
+):
+ if wallet_id != auth.wallet_id:
+ raise HTTPException(HTTPStatus.NOT_FOUND, "Wallet does not exist.")
+ wallet = await get_onchain_wallet(wallet_id)
+ if not wallet or not wallet.onchain_wallet_kind:
+ raise HTTPException(HTTPStatus.NOT_FOUND, "Wallet does not exist.")
+ if wallet.onchain_wallet_kind == "hot":
+ raise HTTPException(
+ HTTPStatus.CONFLICT,
+ "Hot wallets cannot be deleted while they hold signing keys."
+ " Keep the wallet for recovery and transaction history.",
+ )
+ try:
+ await clear_onchain_wallet_data(wallet_id)
+ except ValueError as exc:
+ raise HTTPException(HTTPStatus.CONFLICT, str(exc)) from exc
+ return "", HTTPStatus.NO_CONTENT
+
+
+@wallet_router.put("/onchain/config")
+async def api_update_config(
+ data: OnchainConfig,
+ network: Literal["Mainnet", "Testnet", "Testnet4"] = Query(...),
+ auth: OnchainAuth = Depends(require_onchain_admin),
+) -> OnchainWalletConfigResponse:
+ if data.explorer_provider == "lnbits" and local_explorer_network() != network:
+ raise HTTPException(
+ 400, "LNbits block explorer is unavailable for this network"
+ )
+ wallet = await get_onchain_wallet(auth.wallet_id)
+ if not wallet:
+ raise HTTPException(HTTPStatus.NOT_FOUND, "Wallet does not exist.")
+ if wallet.onchain_wallet_kind and wallet.onchain_network != network:
+ raise HTTPException(
+ HTTPStatus.CONFLICT,
+ "Create another LNbits wallet to use a different Bitcoin network",
+ )
+ await update_onchain_wallet_config(data, wallet_id=auth.wallet_id, network=network)
+ request_scan(auth.wallet_id)
+ response_data = data.dict()
+ response_data["explorer_provider"] = provider_name(data, network)
+ response_data["network"] = network
+ return OnchainWalletConfigResponse(
+ **response_data,
+ lnbits_explorer_network=local_explorer_network(),
+ explorer_url=explorer_url(data, network),
+ )
+
+
+@wallet_router.get("/onchain/config")
+async def api_get_config(
+ auth: OnchainAuth = Depends(require_onchain_read),
+) -> OnchainWalletConfigResponse:
+ wallet = await get_onchain_wallet(auth.wallet_id)
+ if not wallet:
+ raise HTTPException(HTTPStatus.NOT_FOUND, "Wallet does not exist.")
+ config = wallet.onchain_config
+ network = wallet.onchain_network or "Mainnet"
+ data = config.dict()
+ data["explorer_provider"] = provider_name(config, network)
+ data["network"] = network
+ return OnchainWalletConfigResponse(
+ **data,
+ lnbits_explorer_network=local_explorer_network(),
+ explorer_url=explorer_url(config, network),
)
diff --git a/lnbits/decorators.py b/lnbits/decorators.py
index 59b770e..a71f970 100644
--- a/lnbits/decorators.py
+++ b/lnbits/decorators.py
@@ -1,3 +1,4 @@
+from dataclasses import dataclass
from http import HTTPStatus
from typing import Annotated, Literal
@@ -58,6 +59,11 @@ api_key_query = APIKeyQuery(
)
+@dataclass(frozen=True)
+class OnchainAuth:
+ wallet_id: str
+
+
class BaseKeyChecker(SecurityBase):
def __init__(
self,
@@ -226,6 +232,22 @@ async def require_base_invoice_key(
return await check(request)
+async def require_onchain_read(
+ info: WalletTypeInfo = Depends(require_invoice_key),
+) -> OnchainAuth:
+ if not info.wallet.is_onchain_wallet:
+ raise HTTPException(403, "An onchain wallet key is required")
+ return OnchainAuth(wallet_id=info.wallet.id)
+
+
+async def require_onchain_admin(
+ info: WalletTypeInfo = Depends(require_admin_key),
+) -> OnchainAuth:
+ if not info.wallet.is_onchain_wallet:
+ raise HTTPException(403, "An onchain wallet key is required")
+ return OnchainAuth(wallet_id=info.wallet.id)
+
+
async def check_access_token(
header_access_token: Annotated[str | None, Depends(oauth2_scheme)],
cookie_access_token: Annotated[str | None, Cookie()] = None,
diff --git a/lnbits/settings.py b/lnbits/settings.py
index 6e543e6..ad32de1 100644
--- a/lnbits/settings.py
+++ b/lnbits/settings.py
@@ -15,7 +15,7 @@ from typing import Any, Literal
from uuid import uuid4
from loguru import logger
-from pydantic import BaseModel, BaseSettings, Extra, Field, validator
+from pydantic import BaseModel, BaseSettings, Extra, Field, SecretStr, validator
DEFAULT_WASM_MANIFESTS = [
"https://raw.githubusercontent.com/lnbits/lnbits-extensions-wasm/refs/heads/main/extensions.json"
@@ -465,6 +465,7 @@ class ExchangeProvidersSettings(LNbitsSettings):
class SecuritySettings(LNbitsSettings):
+ lnbits_allow_onchain_payments: bool = Field(default=False)
lnbits_rate_limit_no: int = Field(default=200, ge=0)
lnbits_rate_limit_unit: str = Field(default="minute")
lnbits_allowed_ips: list[str] = Field(default=[])
@@ -911,7 +912,7 @@ class BlockExplorerSettings(LNbitsSettings):
lnbits_blockexplorer_electrum_url: str = Field(
default="ssl://electrum.blockstream.info:50002"
)
- # one of: main, test, regtest, signet (see embit.networks.NETWORKS)
+ # one of: main, test, test4, regtest, signet
lnbits_blockexplorer_network: str = Field(default="main")
@@ -1144,6 +1145,11 @@ class UpdateSettings(EditableSettings):
class EnvSettings(LNbitsSettings):
+ lnbits_onchain_master_key: SecretStr | None = Field(
+ default=None,
+ env=["LNBITS_ONCHAIN_MASTER_KEY", "WATCHONLY_MASTER_KEY"],
+ exclude=True,
+ )
debug: bool = Field(default=False)
debug_database: bool = Field(default=False)
bundle_assets: bool = Field(default=True)
diff --git a/lnbits/static/bundle-components.min.js b/lnbits/static/bundle-components.min.js
index 6db905e..a27076e 100644
--- a/lnbits/static/bundle-components.min.js
+++ b/lnbits/static/bundle-components.min.js
@@ -1 +1 @@
-window.PageError={template:"#page-error"},window.PageHome={template:"#page-home",data:()=>({lnurl:"",authAction:"login",authMethod:"username-password",usr:"",username:"",reset_key:"",email:"",password:"",passwordRepeat:"",invitationCode:"",walletName:"",signup:!1}),computed:{showClaimLnurl(){return""!==this.lnurl&&this.g.settings.allowRegister&&this.g.settings.authMethods.includes("user-id-only")},formatDescription(){return LNbits.utils.convertMarkdown(this.g.settings.siteDescription)},isAccessTokenExpired(){return this.$q.cookies.get("is_access_token_expired")}},methods:{showLogin(e){this.authAction="login",this.authMethod=e},showRegister(e){this.user="",this.username=null,this.password=null,this.passwordRepeat=null,this.invitationCode=null,this.authAction="register",this.authMethod=e},async register(){try{await LNbits.api.register(this.username,this.email,this.password,this.passwordRepeat,this.invitationCode),this.refreshAuthUser()}catch(e){LNbits.utils.notifyApiError(e)}},async reset(){try{await LNbits.api.reset(this.reset_key,this.password,this.passwordRepeat),this.refreshAuthUser()}catch(e){LNbits.utils.notifyApiError(e)}},async login(){try{await LNbits.api.login(this.username,this.password),this.refreshAuthUser()}catch(e){LNbits.utils.notifyApiError(e)}},async loginUsr(){try{await LNbits.api.loginUsr(this.usr),this.refreshAuthUser()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async refreshAuthUser(){try{const e=await LNbits.api.getAuthUser();this.g.user=LNbits.map.user(e.data),this.g.isPublicPage=!1,this.$router.push(`/wallet/${this.g.user.wallets[0].id}`)}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},createWallet(){LNbits.api.createAccount(this.walletName).then(e=>{this.$router.push(`/wallet/${e.data.id}`)})},processing(){Quasar.Notify.create({timeout:0,message:"Processing...",icon:null})}},created(){if(this.g.isUserAuthorized)return this.refreshAuthUser();const e=new URLSearchParams(window.location.search);this.reset_key=e.get("reset_key"),this.reset_key&&(this.authAction="reset"),e.has("lightning")&&(this.lnurl=e.get("lightning"))}},window.PageExtensionBuilder={template:"#page-extension-builder",data:()=>({step:1,previewStepNames:{2:"settings",3:"owner_data",4:"client_data",5:"public_page"},extensionDataCleanString:"",extensionData:{id:"",name:"",stub_version:"",short_description:"",description:"",public_page:{has_public_page:!0,owner_data_fields:{name:"",description:""},client_data_fields:{public_inputs:[]},action_fields:{generate_action:!0,generate_payment_logic:!1,wallet_id:"",currency:"",amount:"",paid_flag:""}},preview_action:{is_preview_mode:!1,is_settings_preview:!1,is_owner_data_preview:!1,is_client_data_preview:!1,is_public_page_preview:!1},settings_data:{name:"Settings",enabled:!0,type:"user",fields:[]},owner_data:{name:"OwnerData",fields:[]},client_data:{enabled:!0,name:"ClientData",fields:[]}},sampleField:{name:"name",type:"str",label:"Name",hint:"",optional:!0,editable:!0,searchable:!0,sortable:!0},settingsTypes:[{label:"User Settings",value:"user"},{label:"Admin Settings",value:"admin"}],amountSource:[{label:"Client Data",value:"client_data"},{label:"Owner Data",value:"owner_data"}],extensionStubVersions:[]}),watch:{"extensionData.public_page.action_fields.amount_source":function(e,t){t&&e!==t&&(this.extensionData.public_page.action_fields.amount="")}},computed:{paymentActionAmountFields(){const e=this.extensionData.public_page.action_fields.amount_source;return e?"owner_data"===e?[""].concat(this.extensionData.owner_data.fields.filter(e=>"int"===e.type||"float"===e.type).map(e=>e.name)):"client_data"===e?[""].concat(this.extensionData.client_data.fields.filter(e=>"int"===e.type||"float"===e.type).map(e=>e.name)):void 0:[""]}},methods:{saveState(){this.$q.localStorage.set("lnbits.extension.builder.data",JSON.stringify(this.extensionData)),this.$q.localStorage.set("lnbits.extension.builder.step",this.step)},nextStep(){this.saveState(),this.$refs.stepper.next(),this.refreshPreview()},previousStep(){this.saveState(),this.$refs.stepper.previous(),this.refreshPreview()},onStepChange(){this.saveState(),this.refreshPreview()},clearAllData(){LNbits.utils.confirmDialog("Are you sure you want to clear all data? This action cannot be undone.").onOk(()=>{this.extensionData=JSON.parse(this.extensionDataCleanString),this.$q.localStorage.remove("lnbits.extension.builder.data"),this.$refs.stepper.set(1)})},exportJsonData(){!0!==Quasar.exportFile(`${this.extensionData.id||"data-export"}.json`,JSON.stringify(this.extensionData,null,2),"text/json")?Quasar.Notify.create({message:"Browser denied file download...",color:"negative",icon:null}):Quasar.Notify.create({message:"File downloaded!",color:"positive",icon:"file_download"})},onJsonDataInput(e){const t=e.target.files[0],s=new FileReader;s.onload=e=>{this.extensionData={...this.extensionData,...JSON.parse(e.target.result)},this.$refs.extensionDataInput.value=null,Quasar.Notify.create({message:"File loaded!",color:"positive",icon:"file_upload"})},s.readAsText(t)},async buildExtension(){try{const e={responseType:"blob"},t=await LNbits.api.request("POST","/api/v1/extension/builder/zip",null,this.extensionData,e),s=window.URL.createObjectURL(new Blob([t.data])),i=document.createElement("a");i.href=s,i.download=`${this.extensionData.id||"lnbits-extension"}.zip`,document.body.appendChild(i),i.click(),i.remove(),window.URL.revokeObjectURL(s)}catch(e){LNbits.utils.notifyApiError(e)}},async buildExtensionAndDeploy(){try{const{data:e}=await LNbits.api.request("POST","/api/v1/extension/builder/deploy",null,this.extensionData);Quasar.Notify.create({message:e.message||"Extension deployed!",color:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}},async cleanCacheData(){LNbits.utils.confirmDialog("Are you sure you want to clean the cache data? This action cannot be undone.","Clean Cache Data").onOk(async()=>{try{const{data:e}=await LNbits.api.request("DELETE","/api/v1/extension/builder",null,{});Quasar.Notify.create({message:e.message||"Cache data cleaned!",color:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}})},async previewExtension(e){this.saveState();try{await LNbits.api.request("POST","/api/v1/extension/builder/preview",null,{...this.extensionData,preview_action:{is_preview_mode:!!e,is_settings_preview:"settings"===e,is_owner_data_preview:"owner_data"===e,is_client_data_preview:"client_data"===e,is_public_page_preview:"public_page"===e}}),this.refreshIframe(e)}catch(e){LNbits.utils.notifyApiError(e)}},async refreshPreview(){setTimeout(()=>{const e=this.previewStepNames[`${this.step}`]||"";e&&this.previewExtension(e)},100)},async getStubExtensionReleases(){try{const e="extension_builder_stub",{data:t}=await LNbits.api.request("GET",`/api/v1/extension/${e}/releases`);this.extensionStubVersions=t;const s=t.filter(e=>e.is_version_compatible);this.extensionData.stub_version=s[0]?s[0].version:""}catch(e){LNbits.utils.notifyApiError(e)}},refreshIframe(e=""){const t=this.$refs[`iframeStep${this.step}`];if(!t)return void console.warn("Extension Builder Preview iframe not loaded yet.");t.onload=()=>{const e=t.contentDocument||t.contentWindow.document;e.body.style.transform="scale(0.8)",e.body.style.transformOrigin="center top"};let s="Page"+this.extensionData.id.toLowerCase().split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("");"public_page"===e&&(s+="Public"),t.src=`/extensions/builder/preview?ext_id=${this.extensionData.id}&page=${e}&component=${s}`},initBasicData(){this.extensionData.owner_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.client_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.settings_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionDataCleanString=JSON.stringify(this.extensionData)}},created(){this.initBasicData();const e=this.$q.localStorage.getItem("lnbits.extension.builder.data");e&&(this.extensionData={...this.extensionData,...JSON.parse(e)});const t=+this.$q.localStorage.getItem("lnbits.extension.builder.step");t&&(this.step=t),this.g.user.admin&&this.getStubExtensionReleases(),setTimeout(()=>{this.refreshIframe()},1e3)}},window.PageExtensionBuilder={template:"#page-extension-builder",data:()=>({step:1,previewStepNames:{2:"settings",3:"owner_data",4:"client_data",5:"public_page"},extensionDataCleanString:"",extensionData:{id:"",name:"",stub_version:"",short_description:"",description:"",public_page:{has_public_page:!0,owner_data_fields:{name:"",description:""},client_data_fields:{public_inputs:[]},action_fields:{generate_action:!0,generate_payment_logic:!1,wallet_id:"",currency:"",amount:"",paid_flag:""}},preview_action:{is_preview_mode:!1,is_settings_preview:!1,is_owner_data_preview:!1,is_client_data_preview:!1,is_public_page_preview:!1},settings_data:{name:"Settings",enabled:!0,type:"user",fields:[]},owner_data:{name:"OwnerData",fields:[]},client_data:{enabled:!0,name:"ClientData",fields:[]}},sampleField:{name:"name",type:"str",label:"Name",hint:"",optional:!0,editable:!0,searchable:!0,sortable:!0},settingsTypes:[{label:"User Settings",value:"user"},{label:"Admin Settings",value:"admin"}],amountSource:[{label:"Client Data",value:"client_data"},{label:"Owner Data",value:"owner_data"}],extensionStubVersions:[]}),watch:{"extensionData.public_page.action_fields.amount_source":function(e,t){t&&e!==t&&(this.extensionData.public_page.action_fields.amount="")}},computed:{paymentActionAmountFields(){const e=this.extensionData.public_page.action_fields.amount_source;return e?"owner_data"===e?[""].concat(this.extensionData.owner_data.fields.filter(e=>"int"===e.type||"float"===e.type).map(e=>e.name)):"client_data"===e?[""].concat(this.extensionData.client_data.fields.filter(e=>"int"===e.type||"float"===e.type).map(e=>e.name)):void 0:[""]}},methods:{saveState(){this.$q.localStorage.set("lnbits.extension.builder.data",JSON.stringify(this.extensionData)),this.$q.localStorage.set("lnbits.extension.builder.step",this.step)},nextStep(){this.saveState(),this.$refs.stepper.next(),this.refreshPreview()},previousStep(){this.saveState(),this.$refs.stepper.previous(),this.refreshPreview()},onStepChange(){this.saveState(),this.refreshPreview()},clearAllData(){LNbits.utils.confirmDialog("Are you sure you want to clear all data? This action cannot be undone.").onOk(()=>{this.extensionData=JSON.parse(this.extensionDataCleanString),this.$q.localStorage.remove("lnbits.extension.builder.data"),this.$refs.stepper.set(1)})},exportJsonData(){!0!==Quasar.exportFile(`${this.extensionData.id||"data-export"}.json`,JSON.stringify(this.extensionData,null,2),"text/json")?Quasar.Notify.create({message:"Browser denied file download...",color:"negative",icon:null}):Quasar.Notify.create({message:"File downloaded!",color:"positive",icon:"file_download"})},onJsonDataInput(e){const t=e.target.files[0],s=new FileReader;s.onload=e=>{this.extensionData={...this.extensionData,...JSON.parse(e.target.result)},this.$refs.extensionDataInput.value=null,Quasar.Notify.create({message:"File loaded!",color:"positive",icon:"file_upload"})},s.readAsText(t)},async buildExtension(){try{const e={responseType:"blob"},t=await LNbits.api.request("POST","/api/v1/extension/builder/zip",null,this.extensionData,e),s=window.URL.createObjectURL(new Blob([t.data])),i=document.createElement("a");i.href=s,i.download=`${this.extensionData.id||"lnbits-extension"}.zip`,document.body.appendChild(i),i.click(),i.remove(),window.URL.revokeObjectURL(s)}catch(e){LNbits.utils.notifyApiError(e)}},async buildExtensionAndDeploy(){try{const{data:e}=await LNbits.api.request("POST","/api/v1/extension/builder/deploy",null,this.extensionData);Quasar.Notify.create({message:e.message||"Extension deployed!",color:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}},async cleanCacheData(){LNbits.utils.confirmDialog("Are you sure you want to clean the cache data? This action cannot be undone.","Clean Cache Data").onOk(async()=>{try{const{data:e}=await LNbits.api.request("DELETE","/api/v1/extension/builder",null,{});Quasar.Notify.create({message:e.message||"Cache data cleaned!",color:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}})},async previewExtension(e){this.saveState();try{await LNbits.api.request("POST","/api/v1/extension/builder/preview",null,{...this.extensionData,preview_action:{is_preview_mode:!!e,is_settings_preview:"settings"===e,is_owner_data_preview:"owner_data"===e,is_client_data_preview:"client_data"===e,is_public_page_preview:"public_page"===e}}),this.refreshIframe(e)}catch(e){LNbits.utils.notifyApiError(e)}},async refreshPreview(){setTimeout(()=>{const e=this.previewStepNames[`${this.step}`]||"";e&&this.previewExtension(e)},100)},async getStubExtensionReleases(){try{const e="extension_builder_stub",{data:t}=await LNbits.api.request("GET",`/api/v1/extension/${e}/releases`);this.extensionStubVersions=t;const s=t.filter(e=>e.is_version_compatible);this.extensionData.stub_version=s[0]?s[0].version:""}catch(e){LNbits.utils.notifyApiError(e)}},refreshIframe(e=""){const t=this.$refs[`iframeStep${this.step}`];if(!t)return void console.warn("Extension Builder Preview iframe not loaded yet.");t.onload=()=>{const e=t.contentDocument||t.contentWindow.document;e.body.style.transform="scale(0.8)",e.body.style.transformOrigin="center top"};let s="Page"+this.extensionData.id.toLowerCase().split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("");"public_page"===e&&(s+="Public"),t.src=`/extensions/builder/preview?ext_id=${this.extensionData.id}&page=${e}&component=${s}`},initBasicData(){this.extensionData.owner_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.client_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.settings_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionDataCleanString=JSON.stringify(this.extensionData)}},created(){this.initBasicData();const e=this.$q.localStorage.getItem("lnbits.extension.builder.data");e&&(this.extensionData={...this.extensionData,...JSON.parse(e)});const t=+this.$q.localStorage.getItem("lnbits.extension.builder.step");t&&(this.step=t),this.g.user.admin&&this.getStubExtensionReleases(),setTimeout(()=>{this.refreshIframe()},1e3)}},window.PageExtensionBuilderPreview={template:"#page-extension-builder-preview",mixins:[windowMixin],watch:{name:"reload"},data:()=>({extId:"",pageName:"",componentName:null}),methods:{async reload(){await LNbits.utils.loadTemplate(`/extensions/builder/preview/${this.extId}/template?page_name=${this.pageName}`),await LNbits.utils.loadScript(`/extensions/builder/preview/${this.extId}/component?page_name=${this.pageName}`),this._component=window[this.componentName],console.log("LNbits preview reloaded componentName:",this.componentName,!!this._component),this.$forceUpdate()}},async created(){const e=new URLSearchParams(window.location.search);this.extId=e.get("ext_id")||"",this.pageName=e.get("page")||"",this.componentName=e.get("component")||"",await this.reload()},render(){return this._component?Vue.h(this._component):Vue.h("div","Loading...")}};const EXTENSION_PERMISSION_DEFAULT_MAX_ROWS_PER_SOURCE=1e4,EXTENSION_PERMISSION_MAX_ROWS_PER_SOURCE_LIMIT=1e6,EXTENSION_PERMISSION_MAX_MESSAGES_PER_SECOND_LIMIT=100;window.PageExtensions={template:"#page-extensions",data(){return{extbuilderEnabled:!1,slide:0,fullscreen:!1,autoplay:!0,searchTerm:"",tab:"installed",manageExtensionTab:"releases",filteredExtensions:[],categories:new Set,updatableExtensions:[],showUninstallDialog:!1,showManageExtensionDialog:!1,showExtensionDetailsDialog:!1,showDropDbDialog:!1,showPayToEnableDialog:!1,showUpdateAllDialog:!1,dropDbExtensionId:"",selectedExtension:null,selectedImage:null,selectedExtensionDetails:null,selectedExtensionDetailsDescription:"",selectedExtensionRepos:null,selectedRelease:null,permissionGrant:{show:!1,permissions:[],resolve:null},extensionPermissionMaxRowsPerSourceLimit:1e6,extensionPermissionMaxMessagesPerSecondLimit:100,managedExtensionPermissions:{loading:!1,extensionPermissions:[],userPermissions:{},savingExtensionPermissions:!1,savingKey:"",deletingKey:""},backgroundPaymentDestinationOptions:[{label:"Only transfers to my wallets",value:"own_wallets_only"},{label:"Allow external payments",value:"external_allowed"}],uninstallAndDropDb:!1,maxStars:5,paylinkWebsocket:null,searchToggle:!1,reviewsUrl:null,reviewsDialog:{show:!1,extension:null,loading:!1,submitting:!1,form:{name:"",rating:0,comment:""},error:null},reviews:[],reviewsTable:{loading:!1,columns:[{name:"name",align:"left",label:this.$t("Name"),field:"name",sortable:!0},{name:"comment",align:"left",label:this.$t("Comment"),field:"comment"},{name:"created_at",align:"left",label:this.$t("Date"),field:"created_at"},{name:"rating",align:"right",label:"Rating",field:"rating"}],pagination:{rowsPerPage:5,sortBy:"created_at",descending:!0,page:1}},paymentDialog:{show:!1,invoice:"",hash:""}}},watch:{searchTerm(e){this.filterExtensions(e,this.tab)},tab(e){this.filterExtensions(this.searchTerm,e)}},computed:{managedUserPermissionRows(){const e=[],t=this.managedExtensionPermissions.userPermissions||{};return Object.entries(t).forEach(([t,s])=>{Array.isArray(s)&&s.forEach(s=>{if(!s||"object"!=typeof s)return;const i=String(s.id||""),a=String(s.wallet_id||"");i&&a&&e.push({key:i,permissionId:t,label:this.permissionLabelById(t),grantId:i,walletId:a,walletName:this.walletName(a),grant:s})})}),e}},methods:{filterExtensions(e,t){const s=!["installed","all","featured"].includes(t);var i;this.filteredExtensions=this.extensions.filter(e=>"all"!==t||!e.isInstalled).filter(e=>"installed"!==t||e.isInstalled).filter(e=>"installed"!==t||(!!e.isActive||!!this.g.user.admin)).filter(e=>"featured"!==t||e.isFeatured).filter(e=>!s||(e=>e.categories?.includes(t)??!1)(e)).filter((i=e,function(e){return e.name.toLowerCase().includes(i.toLowerCase())||e.shortDescription?.toLowerCase().includes(i.toLowerCase())})).map(e=>({...e,details_link:e.installedRelease?.details_link||e.latestRelease?.details_link}))},async installExtension(e){this.unsubscribeFromPaylinkWs();const t=await this.resolveExtensionPermissionGrant(e);null!==t&&(this.selectedExtension.inProgress=!0,this.showManageExtensionDialog=!1,e.payment_hash=e.payment_hash||this.getPaylinkHash(e.pay_link),LNbits.api.request("POST","/api/v1/extension",this.g.user.wallets[0].adminkey,{ext_id:this.selectedExtension.id,archive:e.archive,source_repo:e.source_repo,payment_hash:e.payment_hash,version:e.version,permissions:t}).then(t=>{this.selectedExtension.inProgress=!1;const s=this.extensions.find(e=>e.id===this.selectedExtension.id);s.isAvailable=!0,s.isInstalled=!0,s.isWasm=!0===t.data.is_wasm||!0===t.data.isWasm||"wasm"===e.extension_type||!0===s.isWasm,s.icon=t.data.icon||s.icon,s.installedRelease=e,this.toggleExtension(s),s.inProgress=!1,this.selectedExtension=s,this.extensions=this.extensions.concat([]),this.tab="installed"}).catch(e=>{console.warn(e),this.selectedExtension.inProgress=!1,LNbits.utils.notifyApiError(e)}))},async uninstallExtension(){this.showManageExtensionDialog=!1,this.showUninstallDialog=!1,this.selectedExtension.inProgress=!0,LNbits.api.request("DELETE",`/api/v1/extension/${this.selectedExtension.id}`,this.g.user.wallets[0].adminkey).then(e=>{const t=this.extensions.find(e=>e.id===this.selectedExtension.id);t.isAvailable=!1,t.isInstalled=!1,t.inProgress=!1,t.installedRelease=null,this.filteredExtensions=this.filteredExtensions.filter(e=>e.id!==t.id),Quasar.Notify.create({type:"positive",message:"Extension uninstalled!"}),this.uninstallAndDropDb&&this.showDropDb()}).catch(e=>{LNbits.utils.notifyApiError(e),extension.inProgress=!1})},async dropExtensionDb(){const e=this.selectedExtension;this.showManageExtensionDialog=!1,this.showDropDbDialog=!1,this.dropDbExtensionId="",e.inProgress=!0,LNbits.api.request("DELETE",`/api/v1/extension/${e.id}/db`,this.g.user.wallets[0].adminkey).then(t=>{e.installedRelease=null,e.inProgress=!1,e.hasDatabaseTables=!1,Quasar.Notify.create({type:"positive",message:"Extension DB deleted!"})}).catch(t=>{LNbits.utils.notifyApiError(t),e.inProgress=!1})},toggleExtension(e){const t=e.isActive?"activate":"deactivate";LNbits.api.request("PUT",`/api/v1/extension/${e.id}/${t}`,this.g.user.wallets[0].adminkey).then(s=>{Quasar.Notify.create({timeout:2e3,type:"positive",message:`Extension '${e.id}' ${t}d!`})}).catch(t=>{LNbits.utils.notifyApiError(t),e.isActive=!1,e.inProgress=!1})},async enableExtensionForUser(e){e.isPaymentRequired?this.showPayToEnable(e):this.enableExtension(e)},async enableExtension(e){LNbits.api.request("PUT",`/api/v1/extension/${e.id}/enable`,this.g.user.wallets[0].adminkey).then(t=>{this.g.user.extensions=this.g.user.extensions.concat([e.id]),Quasar.Notify.create({type:"positive",message:"Extension enabled!"})}).catch(e=>{console.warn(e),LNbits.utils.notifyApiError(e)})},disableExtension(e){LNbits.api.request("PUT",`/api/v1/extension/${e.id}/disable`,this.g.user.wallets[0].adminkey).then(t=>{this.g.user.extensions=this.g.user.extensions.filter(t=>t!==e.id),Quasar.Notify.create({type:"positive",message:"Extension disabled!"})}).catch(e=>{console.warn(error),LNbits.utils.notifyApiError(e)})},showPayToEnable(e){this.selectedExtension=e,this.selectedExtension.payToEnable.paidAmount=e.payToEnable.amount,this.selectedExtension.payToEnable.showQRCode=!1,this.showPayToEnableDialog=!0},updatePayToInstallData(e){LNbits.api.request("PUT",`/api/v1/extension/${e.id}/sell`,this.g.user.wallets[0].adminkey,{required:e.payToEnable.required,amount:e.payToEnable.amount,wallet:e.payToEnable.wallet}).then(e=>{Quasar.Notify.create({type:"positive",message:"Payment info updated!"}),this.showManageExtensionDialog=!1}).catch(t=>{LNbits.utils.notifyApiError(t),e.inProgress=!1})},showUninstall(){this.showManageExtensionDialog=!1,this.showUninstallDialog=!0,this.uninstallAndDropDb=!1},showDropDb(){this.showDropDbDialog=!0},async showManageExtension(e){if(this.selectedExtension=e,this.selectedRelease=null,this.selectedExtensionRepos=null,this.resetManagedExtensionPermissions(),this.manageExtensionTab=this.g.user.admin?"releases":"extension-permissions",this.showManageExtensionDialog=!0,this.canManageExtensionPermissions(e)&&this.loadManagedExtensionPermissions(e),this.g.user.admin)try{const{data:t}=await LNbits.api.request("GET",`/api/v1/extension/${e.id}/releases`);this.selectedExtensionRepos=t.reduce((e,t)=>(e[t.source_repo]=e[t.source_repo]||{releases:[],isInstalled:!1,repo:t.repo},t.inProgress=!1,t.error=null,t.loaded=!1,t.isInstalled=this.isInstalledVersion(this.selectedExtension,t),t.isInstalled&&(e[t.source_repo].isInstalled=!0),t.pay_link&&(t.requiresPayment=!0,t.paidAmount=t.cost_sats,t.payment_hash=this.getPaylinkHash(t.pay_link)),e[t.source_repo].releases.push(t),e),{})}catch(t){LNbits.utils.notifyApiError(t),e.inProgress=!1}},canShowManageExtensionButton(e){return this.g.user.admin||!0===e?.isWasm&&!0===e?.isInstalled},canManageExtensionPermissions(e=this.selectedExtension){return!0===e?.isWasm&&!0===e?.isInstalled},canShowAdminManageTabs(){return!0===this.g.user.admin},resetManagedExtensionPermissions(){this.managedExtensionPermissions={loading:!1,extensionPermissions:[],userPermissions:{},savingExtensionPermissions:!1,savingKey:"",deletingKey:""}},async loadManagedExtensionPermissions(e=this.selectedExtension){if(this.canManageExtensionPermissions(e)){this.managedExtensionPermissions.loading=!0;try{const{data:t}=await LNbits.api.request("GET",`/api/v1/extension/${e.id}/permissions`);this.managedExtensionPermissions.extensionPermissions=this.cloneEditableExtensionPermissions(t.extension_permissions||[]),this.managedExtensionPermissions.userPermissions=this.cloneUserPermissions(t.user_permissions||{})}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.managedExtensionPermissions.loading=!1}}},cloneEditableExtensionPermissions(e){return(e||[]).filter(e=>e&&"object"==typeof e).map(e=>({...e,policies:Array.isArray(e.policies)?e.policies.map(t=>this.cloneEditablePermissionPolicy(e.id,t)):e.policies}))},cloneEditablePermissionPolicy(e,t){if(!t||"object"!=typeof t||Array.isArray(t))return t;const s=Object.entries(t).reduce((e,[t,s])=>({...e,[t]:Array.isArray(s)?s.slice():s}),{});return"ext.storage.append_public"===e&&(s.max_rows_per_source=this.maxRowsPerSourceValue(s.max_rows_per_source,1e4)),"websocket.publish"===e&&(s.max_messages_per_second=Number(s.max_messages_per_second)),s},maxRowsPerSourceValue(e,t){const s=Number(e);return!Number.isInteger(s)||s<=0?t:Math.min(s,1e6)},extensionPermissionLimitError(e){const t=(e||[]).find(e=>"ext.storage.append_public"===e?.id);if(!t||!Array.isArray(t.policies))return this.websocketPublishLimitError(e);for(const e of t.policies){if(!e||"object"!=typeof e)continue;const t=Number(e.max_rows_per_source);if(!Number.isInteger(t)||t<=0)return"Max rows per source must be a positive integer.";if(t>1e6)return"Max rows per source cannot exceed 1000000."}return this.websocketPublishLimitError(e)},websocketPublishLimitError(e){const t=(e||[]).find(e=>"websocket.publish"===e?.id);if(!t)return"";if(!Array.isArray(t.policies)||1!==t.policies.length)return"Websocket publish requires a max messages per second policy.";const s=t.policies[0];if(!s||"object"!=typeof s)return"Websocket publish requires a max messages per second policy.";const i=Number(s.max_messages_per_second);return!Number.isInteger(i)||i<=0?"Max messages per second must be a positive integer.":i>100?"Max messages per second cannot exceed 100.":""},validateExtensionPermissionLimits(e){const t=this.extensionPermissionLimitError(e);return!t||(Quasar.Notify.create({type:"negative",message:t}),!1)},extensionPermissionsHaveEditableLimits:e=>(e||[]).some(e=>"ext.storage.append_public"===e?.id&&Array.isArray(e.policies)&&e.policies.length>0||"websocket.publish"===e?.id),async saveManagedExtensionPermissions(){const e=this.managedExtensionPermissions.extensionPermissions;if(this.validateExtensionPermissionLimits(e)){this.managedExtensionPermissions.savingExtensionPermissions=!0;try{const{data:t}=await LNbits.api.request("PUT",`/api/v1/extension/${this.selectedExtension.id}/permissions`,this.g.user.wallets[0].adminkey,{permissions:this.cloneEditableExtensionPermissions(e)});this.managedExtensionPermissions.extensionPermissions=this.cloneEditableExtensionPermissions(t.extension_permissions||[]),Quasar.Notify.create({type:"positive",message:"Permission updated."})}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.managedExtensionPermissions.savingExtensionPermissions=!1}}},cloneUserPermissions(e){const t={};return Object.entries(e||{}).forEach(([e,s])=>{Array.isArray(s)&&(t[e]=s.filter(e=>e&&"object"==typeof e).map(e=>({...e,_original:{...e}})))}),t},async showExtensionDetails(e,t){if(t){this.selectedExtension=this.extensions.find(t=>t.id===e)||this.selectedExtension,this.selectedExtensionDetails=null,this.selectedExtensionDetailsDescription="",this.showExtensionDetailsDialog=!0,this.slide=0,this.fullscreen=!1;try{const{data:s}=await LNbits.api.request("GET",`/api/v1/extension/${e}/details?details_link=${t}`);this.selectedExtensionDetails=s,this.selectedExtensionDetailsDescription=this.extensionDescriptionDocument(s.description_md)}catch(e){console.warn(e)}}},extensionDescriptionDocument(e){const t="string"==typeof e?e:"",s=LNbits.utils.convertMarkdown(t),i=(new DOMParser).parseFromString(s,"text/html");i.body.querySelectorAll("applet, base, embed, form, frame, iframe, link, meta, object, portal, script").forEach(e=>e.remove()),i.body.querySelectorAll("*").forEach(e=>{for(const t of[...e.attributes]){const s=t.name.toLowerCase();(s.startsWith("on")||"srcdoc"===s||"xlink:href"===s)&&e.removeAttribute(t.name)}}),i.body.querySelectorAll("a[href], area[href]").forEach(e=>{try{const t=new URL(e.getAttribute("href"),window.location.origin);if(!["http:","https:"].includes(t.protocol)||t.username||t.password)return void e.removeAttribute("href");e.setAttribute("href",t.href),e.setAttribute("target","_blank"),e.setAttribute("rel","noopener noreferrer")}catch(t){e.removeAttribute("href")}});return`<!doctype html>\n <html>\n <head>\n <meta charset="utf-8">\n <meta http-equiv="Content-Security-Policy" content="${["default-src 'none'","img-src https: data:","style-src 'unsafe-inline'","script-src 'none'","script-src-attr 'none'","base-uri 'none'","form-action 'none'","frame-src 'none'","object-src 'none'"].join("; ")}">\n <meta name="referrer" content="no-referrer">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <style>\n :root { color-scheme: light dark; font-family: Roboto, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }\n body { margin: 0; color: CanvasText; background: Canvas; line-height: 1.5; overflow-wrap: anywhere; }\n img { max-width: 100%; height: auto; }\n pre { overflow: auto; padding: 0.75rem; background: color-mix(in srgb, CanvasText 8%, Canvas); }\n code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; }\n table { display: block; max-width: 100%; overflow-x: auto; border-collapse: collapse; }\n th, td { padding: 0.35rem 0.6rem; border: 1px solid color-mix(in srgb, CanvasText 20%, Canvas); }\n a[href] { color: LinkText; cursor: pointer; }\n </style>\n </head>\n <body>\n ${i.body.innerHTML}\n </body>\n </html>`},async payAndInstall(e){try{if(null===await this.resolveExtensionPermissionGrant(e))return;this.selectedExtension.inProgress=!0,this.showManageExtensionDialog=!1;const t=await this.requestPaymentForInstall(this.selectedExtension.id,e);this.rememberPaylinkHash(e.pay_link,t.payment_hash);const s=this.g.user.wallets.find(t=>t.id===e.wallet),{data:i}=await LNbits.api.payInvoice(s,t.payment_request);e.payment_hash=i.payment_hash,await this.installExtension(e)}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.selectedExtension.inProgress=!1}},async payAndEnable(e){try{const t=await this.requestPaymentForEnable(e.id,e.payToEnable.paidAmount),s=this.g.user.wallets.find(t=>t.id===e.payToEnable.paymentWallet),{data:i}=await LNbits.api.payInvoice(s,t.payment_request);this.enableExtension(e),this.showPayToEnableDialog=!1}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async showInstallQRCode(e){if(null!==await this.resolveExtensionPermissionGrant(e)){this.selectedRelease=e,this.showManageExtensionDialog=!0;try{const t=await this.requestPaymentForInstall(this.selectedExtension.id,e);this.selectedRelease.paymentRequest=t.payment_request,this.selectedRelease.payment_hash=t.payment_hash,this.selectedRelease=_.clone(this.selectedRelease),this.rememberPaylinkHash(this.selectedRelease.pay_link,this.selectedRelease.payment_hash),this.subscribeToPaylinkWs(this.selectedRelease.pay_link,t.payment_hash)}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}}},async showEnableQRCode(e){try{e.payToEnable.showQRCode=!0,this.selectedExtension=_.clone(e);const t=await this.requestPaymentForEnable(e.id,e.payToEnable.paidAmount);e.payToEnable.paymentRequest=t.payment_request,this.selectedExtension=_.clone(e);const s=new URL(window.location);s.protocol="https:"===s.protocol?"wss":"ws",s.pathname=`/api/v1/ws/${t.payment_hash}`;const i=new WebSocket(s);i.addEventListener("message",async({data:t})=>{!1===JSON.parse(t).pending&&(Quasar.Notify.create({type:"positive",message:"Invoice Paid!"}),this.enableExtension(e),i.close())})}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async requestPaymentForInstall(e,t){const{data:s}=await LNbits.api.request("PUT",`/api/v1/extension/${e}/invoice/install`,null,{ext_id:e,archive:t.archive,source_repo:t.source_repo,cost_sats:t.paidAmount,version:t.version});return s},async requestPaymentForEnable(e,t){const{data:s}=await LNbits.api.request("PUT",`/api/v1/extension/${e}/invoice/enable`,null,{amount:t});return s},clearHangingInvoice(e){this.forgetPaylinkHash(e.pay_link),e.payment_hash=null},rememberPaylinkHash(e,t){this.$q.localStorage.set(`lnbits.extensions.paylink.${e}`,t)},getPaylinkHash(e){return this.$q.localStorage.getItem(`lnbits.extensions.paylink.${e}`)},forgetPaylinkHash(e){this.$q.localStorage.remove(`lnbits.extensions.paylink.${e}`)},subscribeToPaylinkWs(e,t){const s=new URL(`${e}/${t}`);s.protocol="https:"===s.protocol?"wss":"ws",this.paylinkWebsocket=new WebSocket(s),this.paylinkWebsocket.addEventListener("message",async({data:e})=>{JSON.parse(e).paid?(Quasar.Notify.create({type:"positive",message:"Invoice Paid!"}),this.installExtension(this.selectedRelease)):Quasar.Notify.create({type:"warning",message:"Invoice tracking lost!"})})},unsubscribeFromPaylinkWs(){try{this.paylinkWebsocket&&this.paylinkWebsocket.close()}catch(e){console.warn(e)}},hasNewVersion(e){if(e.installedRelease&&e.latestRelease)return e.installedRelease.version!==e.latestRelease.version},isInstalledVersion(e,t){if(e.installedRelease)return e.installedRelease.source_repo===t.source_repo&&e.installedRelease.version===t.version},getReleaseIcon:e=>e.is_version_compatible?e.isInstalled?"download_done":"download":"block",getReleaseIconColor:e=>e.is_version_compatible?e.isInstalled?"text-green":"":"text-red",extensionOpenUrl:e=>e.isWasm?`/ext/${e.id}`:`/${e.id}`,permissionLabelById(e){const t=`extension_permission_${String(e).replace(/[^A-Za-z0-9]/g,"_")}`,s=this.$t(t);return s===t?e:s},walletName(e){const t=(this.g.user.wallets||[]).find(t=>t.id===e);return t?t.name||t.id:e},userPermissionRowCaption:e=>`${e.walletName} (${e.walletId.slice(0,8)}...)`,isBackgroundPaymentPermission:e=>"wallet.pay_invoice_background"===e.permissionId,userPermissionGrantPayload(e){return{wallet_id:e.walletId,max_amount:this.positiveInteger(e.grant.max_amount,0),destination_policy:this.backgroundPaymentDestinationPolicy(e.grant.destination_policy)}},positiveInteger(e,t){const s=Number(e);return!Number.isFinite(s)||s<=0?t:Math.floor(s)},backgroundPaymentDestinationPolicy:e=>"external_allowed"===e?"external_allowed":"own_wallets_only",backgroundPaymentGrantIncreased(e,t){const s=e.grant._original||{},i=this.positiveInteger(s.max_amount,0),a=this.backgroundPaymentDestinationPolicy(s.destination_policy);return t.max_amount>i||"own_wallets_only"===a&&"external_allowed"===t.destination_policy},confirmUserPermissionIncrease:()=>new Promise(e=>{let t=!1;const s=s=>{t||(t=!0,e(s))};LNbits.utils.confirmDialog("This increases what the extension can do with this wallet. Continue?").onOk(()=>s(!0)).onCancel(()=>s(!1)).onDismiss(()=>s(!1))}),async saveUserPermissionGrant(e){if(!this.isBackgroundPaymentPermission(e))return;const t=this.userPermissionGrantPayload(e);if(t.max_amount){if(!this.backgroundPaymentGrantIncreased(e,t)||await this.confirmUserPermissionIncrease()){this.managedExtensionPermissions.savingKey=e.key;try{await LNbits.api.request("POST",`/api/v1/extension/${this.selectedExtension.id}/permissions/background-payment`,null,t),Quasar.Notify.create({type:"positive",message:"Permission updated."}),await this.loadManagedExtensionPermissions()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.managedExtensionPermissions.savingKey=""}}}else Quasar.Notify.create({type:"negative",message:"Max payment amount must be greater than zero."})},deleteUserPermissionGrant(e){LNbits.utils.confirmDialog("Remove this permission grant?").onOk(async()=>{this.managedExtensionPermissions.deletingKey=e.key;try{const t=encodeURIComponent(e.grantId);await LNbits.api.request("DELETE",`/api/v1/extension/${this.selectedExtension.id}/permissions/user/${t}`),Quasar.Notify.create({type:"positive",message:"Permission removed."}),await this.loadManagedExtensionPermissions()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.managedExtensionPermissions.deletingKey=""}})},async getGitHubReleaseDetails(e){if(!e.is_github_release||e.loaded)return;const[t,s]=e.source_repo.split("/");e.inProgress=!0;try{const{data:i}=await LNbits.api.request("GET",`/api/v1/extension/release/${t}/${s}/${e.version}`);e.loaded=!0,e.is_version_compatible=i.is_version_compatible,e.min_lnbits_version=i.min_lnbits_version,e.warning=i.warning,e.extension_type=i.extension_type,e.permissions=i.permissions||[]}catch(t){console.warn(t),e.error=t,LNbits.utils.notifyApiError(t)}finally{e.inProgress=!1}},async resolveExtensionPermissionGrant(e){const t=this.extensionPermissionsForRelease(e);if(!this.releaseRequiresPermissionGrant(e)||!t.length)return[];if(e.grantedPermissions)return e.grantedPermissions;const s=await this.confirmExtensionPermissions(t);return s?(e.grantedPermissions=s,s):null},extensionPermissionsForRelease(e){return e.permissions||this.selectedExtension?.permissions||[]},releaseRequiresPermissionGrant(e){return"wasm"===e.extension_type||!0===this.selectedExtension?.isWasm},confirmExtensionPermissions(e){return new Promise(t=>{this.selectedRelease=null,this.permissionGrant={show:!0,permissions:this.cloneEditableExtensionPermissions(e),resolve:t},this.showManageExtensionDialog=!0})},grantExtensionPermissions(){this.validateExtensionPermissionLimits(this.permissionGrant.permissions)&&this.resolveExtensionPermissionDialog(this.cloneEditableExtensionPermissions(this.permissionGrant.permissions))},cancelExtensionPermissions(){this.resolveExtensionPermissionDialog(null)},onManageExtensionDialogHide(){this.permissionGrant.show&&this.resolveExtensionPermissionDialog(null)},resolveExtensionPermissionDialog(e){const t=this.permissionGrant.resolve;this.permissionGrant={show:!1,permissions:[],resolve:null},this.showManageExtensionDialog=!1,t&&t(e)},permissionGrantHasHighRisk(){return window.LNbitsExtensionPermissions.hasHighRisk({permissions:this.permissionGrant.permissions,extensions:this.extensions,translate:e=>this.$t(e)})},async selectAllUpdatableExtensionss(){this.updatableExtensions.forEach(e=>e.selectedForUpdate=!0)},async updateSelectedExtensions(){let e=0;for(const t of this.updatableExtensions)try{if(!t.selectedForUpdate)continue;if(t.isWasm){Quasar.Notify.create({type:"warning",message:`Skipping ${t.id}; this extension update requires permission approval.`});continue}t.inProgress=!0,await LNbits.api.request("POST","/api/v1/extension",null,{ext_id:t.id,archive:t.latestRelease.archive,source_repo:t.latestRelease.source_repo,payment_hash:t.latestRelease.payment_hash,version:t.latestRelease.version}),e++,t.isAvailable=!0,t.isInstalled=!0,t.isUpgraded=!0,t.inProgress=!1,t.installedRelease=t.latestRelease,t.isActive=!0,this.toggleExtension(t)}catch(e){console.warn(e),Quasar.Notify.create({type:"negative",message:`Failed to update ${t.id}!`})}finally{t.inProgress=!1}Quasar.Notify.create({type:e?"positive":"warning",message:`${e||"No"} extensions updated!`}),this.showUpdateAllDialog=!1},formatAvg(e){const t=Number(e||0);return Math.round(t/2/100*2)/2},async loadReviewStats(){if(this.reviewsUrl)try{const{data:e}=await LNbits.api.request("GET","/api/v1/extension/reviews/tags"),t={};e.forEach(e=>{t[e.tag]=e}),this.extensions.forEach(e=>{e.reviewStats=t[e.id]||null}),this.filterExtensions(this.searchTerm,this.tab)}catch(e){console.warn(e)}else console.info("Extension reviews are not configured")},async openReviews(e){const t=e||(this.selectedExtensionDetails?this.extensions.find(e=>e.id===this.selectedExtensionDetails.id):null);t&&(this.reviewsUrl?(this.reviewsDialog.extension=t,this.selectedExtension=e,this.reviewsDialog.show=!0,await this.getTagReviews()):Quasar.Notify.create({type:"warning",message:this.$t("reviews_url_not_configured")}))},async getTagReviews(e){if(this.reviewsUrl)try{this.reviewsTable.loading=!0;const t=LNbits.utils.prepareFilterQuery(this.reviewsTable,e),{data:s}=await LNbits.api.request("GET",`/api/v1/extension/reviews/${this.selectedExtension.id}?${t}`);this.reviews=s.data,this.reviewsTable.pagination.rowsNumber=s.total}catch(e){LNbits.utils.notifyApiError(e)}finally{this.reviewsTable.loading=!1}else Quasar.Notify.create({type:"warning",message:this.$t("reviews_url_not_configured")})},formatReviewDate(e){if(!e)return"";const t=Number(e);return Number.isNaN(t)?this.utils.formatDate(e):this.utils.formatTimestamp(t)},async submitReview(){if(this.reviewsDialog.extension&&this.reviewsUrl){this.reviewsDialog.submitting=!0;try{const e={tag:this.reviewsDialog.extension.id,name:this.reviewsDialog.form.name,rating:100*this.reviewsDialog.form.rating,comment:this.reviewsDialog.form.comment},{data:t}=await LNbits.api.request("PUT","/api/v1/extension/reviews",null,e);t.payment_request?this.openInvoiceDialog(t.payment_request,t.payment_hash):(Quasar.Notify.create({type:"positive",message:"Review submitted"}),this.resetReviewForm(),await this.getTagReviews(),await this.loadReviewStats())}catch(e){LNbits.utils.notifyApiError(e)}finally{this.reviewsDialog.submitting=!1}}},openInvoiceDialog(e,t){this.paymentDialog.invoice=e,this.paymentDialog.hash=t,this.paymentDialog.show=!0,this.listenForPayment(t)},resetReviewForm(){this.reviewsDialog.form={name:"",rating:0,comment:""},this.paymentDialog={show:!1,invoice:"",hash:""}},listenForPayment(e){try{const t=new URL(this.reviewsUrl);t.protocol="https:"===t.protocol?"wss:":"ws:",t.pathname=`/api/v1/ws/${e}`;const s=new WebSocket(t);s.addEventListener("message",async()=>{Quasar.Notify.create({type:"positive",message:this.$t("reviews_invoice_paid")}),this.paymentDialog.show=!1,this.resetReviewForm(),setTimeout(async()=>{await this.getTagReviews()},1e3),await this.loadReviewStats(),s.close()})}catch(e){console.warn(e)}},async fetchAllExtensions(){try{const{data:e}=await LNbits.api.request("GET","/api/v1/extension/all");return e.forEach(e=>{e.categories?.forEach(e=>this.categories.add(e))}),e}catch(e){return console.warn(e),LNbits.utils.notifyApiError(e),[]}}},async created(){this.extensions=await this.fetchAllExtensions(),this.extbuilderEnabled=this.g.user.admin||this.g.settings.extBuilder,this.reviewsUrl=this.g.settings.extensionsReviewsUrl,0===this.g.user.extensions.length&&(this.tab="all");const e=window.location.hash.replace("#",""),t=this.extensions.find(t=>t.id===e);t&&(this.searchTerm=t.id,t.isInstalled&&(this.tab="installed")),this.updatableExtensions=this.extensions.filter(e=>this.hasNewVersion(e)),await this.loadReviewStats(),this.filterExtensions(this.searchTerm,this.tab)}},window.PageFirstInstall={template:"#page-first-install",data:()=>({loginData:{isPwd:!0,isPwdRepeat:!0,username:"",password:"",passwordRepeat:"",firstInstallToken:""}}),computed:{checkPasswordsMatch(){return this.loginData.password!==this.loginData.passwordRepeat}},methods:{setPassword(){LNbits.api.request("PUT","/api/v1/auth/first_install",null,{username:this.loginData.username,password:this.loginData.password,password_repeat:this.loginData.passwordRepeat,first_install_token:this.loginData.firstInstallToken}).then(async()=>{const e=await LNbits.api.getAuthUser();this.g.user=LNbits.map.user(e.data),this.g.isPublicPage=!1,this.$router.push("/admin")}).catch(this.utils.notifyApiError)}},created(){const e=new URLSearchParams(window.location.search);this.loginData.firstInstallToken=e.get("token")||""}},window.PagePayments={template:"#page-payments",data:()=>({payments:[],dailyChartData:[],searchDate:{from:null,to:null},searchData:{wallet_id:null,payment_hash:null,memo:null,internal_memo:null},statusFilters:{success:!0,pending:!0,failed:!0,incoming:!0,outgoing:!0},chartData:{showPaymentStatus:!0,showPaymentTags:!0,showBalance:!0,showWalletsSize:!1,showBalanceInOut:!1,showPaymentCountInOut:!1},searchOptions:{status:[]},paymentsTable:{columns:[{name:"status",align:"left",label:"Status",field:"status",sortable:!1},{name:"created_at",align:"left",label:"Created At",field:"created_at",sortable:!0},{name:"amount",align:"right",label:"Amount",field:"amount",sortable:!0},{name:"amountFiat",align:"right",label:"Fiat",field:"amountFiat",sortable:!1},{name:"fee_sats",align:"left",label:"Fee",field:"fee_sats",sortable:!0},{name:"tag",align:"left",label:"Tag",field:"tag",sortable:!1},{name:"memo",align:"left",label:"Memo",field:"memo",sortable:!1,max_length:20},{name:"internal_memo",align:"left",label:"Internal Memo",field:"internal_memo",sortable:!1,max_length:20},{name:"wallet_id",align:"left",label:"Wallet (ID)",field:"wallet_id",sortable:!1},{name:"payment_hash",align:"left",label:"Payment Hash",field:"payment_hash",sortable:!1}],pagination:{sortBy:"created_at",rowsPerPage:25,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},chartsReady:!1,showDetails:!1,paymentDetails:null,lnbitsBalance:0}),async mounted(){this.chartsReady=!0,await this.$nextTick(),this.initCharts(),await this.fetchPayments()},computed:{},methods:{async fetchPayments(e){const t=Object.entries(this.searchData).reduce((e,[t,s])=>s?(e[t]=s,e):e,{});delete t["time[ge]"],delete t["time[le]"],this.searchDate.from&&(t["time[ge]"]=this.searchDate.from+"T00:00:00"),this.searchDate.to&&(t["time[le]"]=this.searchDate.to+"T23:59:59"),this.paymentsTable.filter=t;try{const t=LNbits.utils.prepareFilterQuery(this.paymentsTable,e),{data:s}=await LNbits.api.request("GET",`/api/v1/payments/all/paginated?${t}`);this.paymentsTable.pagination.rowsNumber=s.total,this.payments=s.data.map(e=>(e.extra&&e.extra.tag&&(e.tag=e.extra.tag),e.timeFrom=moment.utc(e.created_at).local().fromNow(),e.outgoing=e.amount<0,e.amount=new Intl.NumberFormat(this.g.locale).format(e.amount/1e3)+" sats",e.extra?.wallet_fiat_amount&&(e.amountFiat=this.formatCurrency(e.extra.wallet_fiat_amount,e.extra.wallet_fiat_currency)),e.extra?.internal_memo&&(e.internal_memo=e.extra.internal_memo),e.fee_sats=new Intl.NumberFormat(this.g.locale).format(e.fee/1e3)+" sats",e))}catch(e){console.error(e),LNbits.utils.notifyApiError(e)}finally{this.updateCharts(e)}},async searchPaymentsBy(e,t){e&&(this.searchData[e]=t),await this.fetchPayments()},clearDateSeach(){this.searchDate={from:null,to:null},delete this.paymentsTable.filter["time[ge]"],delete this.paymentsTable.filter["time[le]"],this.fetchPayments()},searchByDate(){"string"==typeof this.searchDate&&(this.searchDate={from:this.searchDate,to:this.searchDate}),this.searchDate.from&&(this.paymentsTable.filter["time[ge]"]=this.searchDate.from+"T00:00:00"),this.searchDate.to&&(this.paymentsTable.filter["time[le]"]=this.searchDate.to+"T23:59:59"),this.fetchPayments()},handleFilterChanged(){const{success:e,pending:t,failed:s,incoming:i,outgoing:a}=this.statusFilters;delete this.searchData["status[ne]"],delete this.searchData["status[eq]"],e&&t&&s||(e&&t?this.searchData["status[ne]"]="failed":e&&s?this.searchData["status[ne]"]="pending":s&&t?this.searchData["status[ne]"]="success":e?this.searchData["status[eq]"]="success":t?this.searchData["status[eq]"]="pending":s&&(this.searchData["status[eq]"]="failed")),delete this.searchData["amount[ge]"],delete this.searchData["amount[le]"],i&&a||(i?this.searchData["amount[ge]"]="0":a&&(this.searchData["amount[le]"]="0")),this.fetchPayments()},showDetailsToggle(e){return this.paymentDetails=e,this.showDetails=!this.showDetails},formatCurrency(e,t){try{return LNbits.utils.formatCurrency(e,t)}catch(t){return console.error(t),`${e} ???`}},shortify:(e,t=10)=>(valueLength=(e||"").length,valueLength<=t?e:`${e.substring(0,5)}...${e.substring(valueLength-5,valueLength)}`),async updateCharts(e){let t=LNbits.utils.prepareFilterQuery(this.paymentsTable,e);try{const{data:e}=await LNbits.api.request("GET",`/api/v1/payments/stats/count?${t}&count_by=status`);e.sort((e,t)=>e.field-t.field).reverse(),this.searchOptions.status=e.map(e=>e.field),this.paymentsStatusChart.data.datasets[0].data=e.map(e=>e.total),this.paymentsStatusChart.data.labels=[...this.searchOptions.status],this.paymentsStatusChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}try{const{data:e}=await LNbits.api.request("GET",`/api/v1/payments/stats/wallets?${t}`),s=e.map(e=>e.balance/e.payments_count),i=Math.min(...s),a=Math.max(...s),n=e=>Math.floor(3+22*(e-i)/(a-i)),o=this.randomColors(20),r=e.map((e,t)=>({data:[{x:e.payments_count,y:e.balance,r:n(Math.max(e.balance/e.payments_count,5))}],label:e.wallet_name,wallet_id:e.wallet_id,backgroundColor:o[t%100],hoverOffset:4}));this.paymentsWalletsChart.data.datasets=r,this.paymentsWalletsChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}try{const{data:e}=await LNbits.api.request("GET",`/api/v1/payments/stats/count?${t}&count_by=tag`);this.searchOptions.tag=e.map(e=>e.field),this.searchOptions.status.sort(),this.paymentsTagsChart.data.datasets[0].data=e.map(e=>e.total),this.paymentsTagsChart.data.labels=e.map(e=>e.field||"core"),this.paymentsTagsChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}try{const t=Object.entries(this.searchData).reduce((e,[t,s])=>s?(e[t]=s,e):e,{}),s={...this.paymentsTable,filter:t},i=LNbits.utils.prepareFilterQuery(s,e);let{data:a}=await LNbits.api.request("GET",`/api/v1/payments/stats/daily?${i}`);const n=this.searchDate.from+"T00:00:00",o=this.searchDate.to+"T23:59:59";this.lnbitsBalance=a.length?a[a.length-1].balance:0,a=a.filter(e=>this.searchDate.from&&this.searchDate.to?e.date>=n&&e.date<=o:this.searchDate.from?e.date>=n:!this.searchDate.to||e.date<=o),this.paymentsDailyChart.data.datasets=[{label:"Balance",data:a.map(e=>e.balance),pointStyle:!1,borderWidth:2,tension:.7,fill:1},{label:"Fees",data:a.map(e=>e.fee),pointStyle:!1,borderWidth:1,tension:.4,fill:1}],this.paymentsDailyChart.data.labels=a.map(e=>e.date.substring(0,10)),this.paymentsDailyChart.update(),this.paymentsBalanceInOutChart.data.datasets=[{label:"Incoming Payments Balance",data:a.map(e=>e.balance_in)},{label:"Outgoing Payments Balance",data:a.map(e=>e.balance_out)}],this.paymentsBalanceInOutChart.data.labels=a.map(e=>e.date.substring(0,10)),this.paymentsBalanceInOutChart.update(),this.paymentsCountInOutChart.data.datasets=[{label:"Incoming Payments Count",data:a.map(e=>e.count_in)},{label:"Outgoing Payments Count",data:a.map(e=>-e.count_out)}],this.paymentsCountInOutChart.data.labels=a.map(e=>e.date.substring(0,10)),this.paymentsCountInOutChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async initCharts(){const e=this.$q.localStorage.getItem("lnbits.payments.chartData")||{};this.chartData={...this.chartData,...e},this.chartsReady?(this.paymentsStatusChart=new Chart(this.$refs.paymentsStatusChart.getContext("2d"),{type:"doughnut",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchPaymentsBy("status",s.data.labels[e])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(0, 205, 86)","rgb(64, 72, 78)","rgb(255, 99, 132)"],hoverOffset:4}]}}),this.paymentsWalletsChart=new Chart(this.$refs.paymentsWalletsChart.getContext("2d"),{type:"bubble",options:{responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!1},title:{display:!1}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].datasetIndex;this.searchPaymentsBy("wallet_id",s.data.datasets[e].wallet_id)}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(20),hoverOffset:4}]}}),this.paymentsTagsChart=new Chart(this.$refs.paymentsTagsChart.getContext("2d"),{type:"pie",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!1,title:{display:!1,text:"Tags"}}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchPaymentsBy("tag",s.data.labels[e])}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(10),hoverOffset:4}]}}),this.paymentsDailyChart=new Chart(this.$refs.paymentsDailyChart.getContext("2d"),{type:"line",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:"Tags"}}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(10),hoverOffset:4}]}}),this.paymentsBalanceInOutChart=new Chart(this.$refs.paymentsBalanceInOutChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:"Tags"}}},scales:{x:{stacked:!0},y:{stacked:!0}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(50),hoverOffset:4}]}}),this.paymentsCountInOutChart=new Chart(this.$refs.paymentsCountInOutChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:""}}},scales:{x:{stacked:!0},y:{stacked:!0}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(80),hoverOffset:4}]}})):console.warn("Charts are not ready yet. Initialization delayed.")},saveChartsPreferences(){this.$q.localStorage.set("lnbits.payments.chartData",this.chartData)},randomColors(e=1){const t=[];for(let s=1;s<=10;s++)for(let i=1;i<=10;i++)t.push(`rgb(${i*e*33%200}, ${71*(s+i+e)%255}, ${(s+30*e)%255})`);return t}}},window.PageNode={template:"#page-node",config:{globalProperties:{LNbits:LNbits,msg:"hello"}},data(){return{isSuperUser:!1,wallet:{},tab:"dashboard",payments:1e3,info:{},phoenixd:{capabilities:[]},phoenixdAmount:2e6,phoenixdEstimate:null,phoenixdReceive:"",phoenixdResult:"",phoenixdDialog:{show:!1,operation:"",data:{}},phoenixdBusy:!1,channel_stats:{},channels:{data:[],filter:""},activeBalance:{},ranks:{},peers:{data:[],filter:""},connectPeerDialog:{show:!1,data:{}},setFeeDialog:{show:!1,data:{fee_ppm:0,fee_base_msat:0}},openChannelDialog:{show:!1,data:{}},closeChannelDialog:{show:!1,data:{}},nodeInfoDialog:{show:!1,data:{}},transactionDetailsDialog:{show:!1,data:{}},states:[{label:"Active",value:"active",color:"green"},{label:"Pending",value:"pending",color:"orange"},{label:"Inactive",value:"inactive",color:"grey"},{label:"Closed",value:"closed",color:"red"}],stateFilters:[{label:"Active",value:"active"},{label:"Pending",value:"pending"}],paymentsTable:{data:[],columns:[{name:"pending",label:""},{name:"date",align:"left",label:this.$t("date"),field:"date",sortable:!0},{name:"sat",align:"right",label:this.$t("amount"),field:e=>this.formatMsat(e.amount),sortable:!0},{name:"fee",align:"right",label:this.$t("fee"),field:"fee"},{name:"destination",align:"right",label:"Destination",field:"destination"},{name:"memo",align:"left",label:this.$t("memo"),field:"memo"}],pagination:{rowsPerPage:10,page:1,rowsNumber:10},filter:null},invoiceTable:{data:[],columns:[{name:"pending",label:""},{name:"paid_at",field:"paid_at",align:"left",label:"Paid at",sortable:!0},{name:"expiry",label:this.$t("expiry"),field:"expiry",align:"left",sortable:!0},{name:"amount",label:this.$t("amount"),field:e=>this.formatMsat(e.amount),sortable:!0},{name:"memo",align:"left",label:this.$t("memo"),field:"memo"}],pagination:{rowsPerPage:10,page:1,rowsNumber:10},filter:null}}},created(){this.getInfo()},watch:{tab(e){"transactions"!==e||this.paymentsTable.data.length?"channels"!==e||this.channels.data.length||(this.getChannels(),this.managedChannels||this.getPeers()):(this.getPayments(),this.getInvoices())}},computed:{managedChannels(){return!0===this.info.managed_channels},canManage(){return!0===this.g.user?.super_user},checkChanges(){return!_.isEqual(this.settings,this.formData)},filteredChannels(){return this.stateFilters?this.channels.data.filter(e=>this.stateFilters.find(({value:t})=>t==e.state)):this.channels.data},totalBalance(){return this.filteredChannels.reduce((e,t)=>(e.local_msat+=t.balance.local_msat,e.remote_msat+=t.balance.remote_msat,e.total_msat+=t.balance.total_msat,e),{local_msat:0,remote_msat:0,total_msat:0})}},methods:{hasPhoenixdCapability(e){return this.phoenixd.capabilities.includes(e)},getPhoenixdStatus(){return this.nodeApi("GET","/phoenixd/status").then(e=>{this.phoenixd=e.data}).catch(()=>{})},estimatePhoenixdLiquidity(){return this.phoenixdEstimate=null,this.nodeApi("GET","/phoenixd/liquidity-fees",{query:{amount_sat:this.phoenixdAmount}}).then(e=>{this.phoenixdEstimate=e.data}).catch(()=>{})},getPhoenixdReceive(e){return this.phoenixdReceive="",this.nodeApi("GET",`/phoenixd/receive/${e}`).then(e=>{this.phoenixdReceive=e.data.value}).catch(()=>{})},showPhoenixdDialog(e,t={}){this.phoenixdDialog={show:!0,operation:e,data:{...t}},this.phoenixdResult=""},submitPhoenixd(){const{operation:e,data:t}=this.phoenixdDialog,s={close:`Close channel ${t.channel_id} and send its remaining balance to ${t.address} at ${t.fee_rate} sat/vB?`,send:`Withdraw ${t.amount_sat} sats to ${t.address} at ${t.fee_rate} sat/vB?`,bump:`Spend node funds to bump the funding transaction fee to a target of ${t.fee_rate} sat/vB?`};LNbits.utils.confirmDialog(s[e]+" This spends funds backing LNbits wallets and cannot be undone.").onOk(async()=>{this.phoenixdBusy=!0;try{const s=await this.nodeApi("POST",`/phoenixd/${e}`,{data:t});this.phoenixdResult=s.data.txid,this.phoenixdDialog.show=!1,await this.getInfo(),await this.getChannels()}catch(e){}finally{this.phoenixdBusy=!1}})},exportPhoenixdHistory(){this.nodeApi("POST","/phoenixd/export").then(e=>{Quasar.Notify.create({message:e.data.message})}).catch(()=>{})},formatMsat:e=>LNbits.utils.formatMsat(e),nodeApi(e,t,s){const i=new URLSearchParams(s?.query);return LNbits.api.request(e,`/node/api/v1${t}?${i}`,{},s?.data).catch(e=>{throw LNbits.utils.notifyApiError(e),e})},getChannel(e){return this.nodeApi("GET",`/channels/${e}`).then(e=>{this.setFeeDialog.data.fee_ppm=e.data.fee_ppm,this.setFeeDialog.data.fee_base_msat=e.data.fee_base_msat})},getChannels(){return this.nodeApi("GET","/channels").then(e=>{this.channels.data=e.data})},getInfo(){return this.nodeApi("GET","/info").then(e=>{const t=this.managedChannels;this.info=e.data,this.channel_stats=e.data.channel_stats,this.managedChannels?(this.getPhoenixdStatus(),t||(this.stateFilters=null)):this.get1MLStats()}).catch(()=>{this.info={},this.channel_stats={}})},get1MLStats(){return this.nodeApi("GET","/rank").then(e=>{this.ranks=e.data}).catch(()=>{this.ranks={}})},getPayments(e){e&&(this.paymentsTable.pagination=e.pagination);let t=this.paymentsTable.pagination;const s={limit:t.rowsPerPage,offset:(t.page-1)*t.rowsPerPage??0};return this.nodeApi("GET","/payments",{query:s}).then(e=>{this.paymentsTable.data=e.data.data,this.paymentsTable.pagination.rowsNumber=e.data.total})},getInvoices(e){e&&(this.invoiceTable.pagination=e.pagination);let t=this.invoiceTable.pagination;const s={limit:t.rowsPerPage,offset:(t.page-1)*t.rowsPerPage??0};return this.nodeApi("GET","/invoices",{query:s}).then(e=>{this.invoiceTable.data=e.data.data,this.invoiceTable.pagination.rowsNumber=e.data.total})},getPeers(){return this.nodeApi("GET","/peers").then(e=>{this.peers.data=e.data})},connectPeer(){this.nodeApi("POST","/peers",{data:this.connectPeerDialog.data}).then(()=>{this.connectPeerDialog.show=!1,this.getPeers()})},disconnectPeer(e){LNbits.utils.confirmDialog("Do you really wanna disconnect this peer?").onOk(()=>{this.nodeApi("DELETE",`/peers/${e}`).then(e=>{Quasar.Notify.create({message:"Disconnected",icon:null}),this.needsRestart=!0,this.getPeers()})})},setChannelFee(e){this.nodeApi("PUT",`/channels/${e}`,{data:this.setFeeDialog.data}).then(e=>{this.setFeeDialog.show=!1,this.getChannels()}).catch(LNbits.utils.notifyApiError)},openChannel(){this.nodeApi("POST","/channels",{data:this.openChannelDialog.data}).then(e=>{this.openChannelDialog.show=!1,this.getChannels()}).catch(e=>{console.log(e)})},showCloseChannelDialog(e){this.managedChannels?this.showPhoenixdDialog("close",{channel_id:e.id}):(this.closeChannelDialog.show=!0,this.closeChannelDialog.data={force:!1,short_id:e.short_id,...e.point})},closeChannel(){this.nodeApi("DELETE","/channels",{query:this.closeChannelDialog.data}).then(e=>{this.closeChannelDialog.show=!1,this.getChannels()})},showSetFeeDialog(e){this.setFeeDialog.show=!0,this.setFeeDialog.channel_id=e,this.getChannel(e)},showOpenChannelDialog(e){this.openChannelDialog.show=!0,this.openChannelDialog.data={peer_id:e,funding_amount:0}},showNodeInfoDialog(e){this.nodeInfoDialog.show=!0,this.nodeInfoDialog.data=e},showTransactionDetailsDialog(e){this.transactionDetailsDialog.show=!0,this.transactionDetailsDialog.data=e},shortenNodeId:e=>e?e.substring(0,5)+"..."+e.substring(e.length-5):"..."}},window.PageNodePublic={template:"#page-node-public",data:()=>({enabled:!1,isSuperUser:!1,wallet:{},tab:"dashboard",payments:1e3,info:{},channel_stats:{},channels:[],activeBalance:{},ranks:{},peers:[],connectPeerDialog:{show:!1,data:{}},openChannelDialog:{show:!1,data:{}},closeChannelDialog:{show:!1,data:{}},nodeInfoDialog:{show:!1,data:{}},states:[{label:"Active",value:"active",color:"green"},{label:"Pending",value:"pending",color:"orange"},{label:"Inactive",value:"inactive",color:"grey"},{label:"Closed",value:"closed",color:"red"}]}),created(){this.getInfo()},methods:{formatMsat:e=>LNbits.utils.formatMsat(e),api:(e,t,s)=>LNbits.api.request(e,"/node/public/api/v1"+t,{},s),getInfo(){this.api("GET","/info",{}).then(e=>{this.info=e.data,this.channel_stats=e.data.channel_stats,this.enabled=!0,this.info.managed_channels||this.get1MLStats()}).catch(()=>{this.info={},this.channel_stats={}})},get1MLStats(){this.api("GET","/rank",{}).then(e=>{this.ranks=e.data}).catch(()=>{this.ranks={}})}}},window.PageAudit={template:"#page-audit",data:()=>({chartsReady:!1,auditEntries:[],searchData:{user_id:"",ip_address:"",request_type:"",component:"",request_method:"",response_code:"",path:""},searchOptions:{component:[],request_method:[],response_code:[]},auditTable:{columns:[{name:"created_at",align:"center",label:"Date",field:"created_at",sortable:!0},{name:"duration",align:"left",label:"Duration (sec)",field:"duration",sortable:!0},{name:"component",align:"left",label:"Component",field:"component",sortable:!1},{name:"request_method",align:"left",label:"Method",field:"request_method",sortable:!1},{name:"response_code",align:"left",label:"Code",field:"response_code",sortable:!1},{name:"user_id",align:"left",label:"User Id",field:"user_id",sortable:!1},{name:"ip_address",align:"left",label:"IP Address",field:"ip_address",sortable:!1},{name:"path",align:"left",label:"Path",field:"path",sortable:!1}],pagination:{sortBy:"created_at",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},auditDetailsDialog:{data:null,show:!1}}),async created(){},async mounted(){this.chartsReady=!0,await this.$nextTick(),this.initCharts(),await this.fetchAudit()},methods:{async fetchAudit(e){try{const t=LNbits.utils.prepareFilterQuery(this.auditTable,e),{data:s}=await LNbits.api.request("GET",`/audit/api/v1?${t}`);this.auditTable.pagination.rowsNumber=s.total,this.auditEntries=s.data,await this.fetchAuditStats(e)}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.auditTable.loading=!1}},async fetchAuditStats(e){try{const t=LNbits.utils.prepareFilterQuery(this.auditTable,e),{data:s}=await LNbits.api.request("GET",`/audit/api/v1/stats?${t}`),i=s.request_method.map(e=>e.field);this.searchOptions.request_method=[...new Set(this.searchOptions.request_method.concat(i))],this.requestMethodChart.data.labels=i,this.requestMethodChart.data.datasets[0].data=s.request_method.map(e=>e.total),this.requestMethodChart.update();const a=s.response_code.map(e=>e.field);this.searchOptions.response_code=[...new Set(this.searchOptions.response_code.concat(a))],this.responseCodeChart.data.labels=a,this.responseCodeChart.data.datasets[0].data=s.response_code.map(e=>e.total),this.responseCodeChart.update();const n=s.component.map(e=>e.field);this.searchOptions.component=[...new Set(this.searchOptions.component.concat(n))],this.componentUseChart.data.labels=n,this.componentUseChart.data.datasets[0].data=s.component.map(e=>e.total),this.componentUseChart.update(),this.longDurationChart.data.labels=s.long_duration.map(e=>e.field),this.longDurationChart.data.datasets[0].data=s.long_duration.map(e=>e.total),this.longDurationChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async searchAuditBy(e,t){e&&(this.searchData[e]=t),this.auditTable.filter=Object.entries(this.searchData).reduce((e,[t,s])=>s?(e[t]=s,e):e,{}),await this.fetchAudit()},showDetailsDialog(e){const t=JSON.parse(e?.request_details||"");try{t.body&&(t.body=JSON.parse(t.body))}catch(e){}this.auditDetailsDialog.data=JSON.stringify(t,null,4),this.auditDetailsDialog.show=!0},shortify:e=>(valueLength=(e||"").length,valueLength<=10?e:`${e.substring(0,5)}...${e.substring(valueLength-5,valueLength)}`),async initCharts(){this.chartsReady?(this.responseCodeChart=new Chart(this.$refs.responseCodeChart.getContext("2d"),{type:"doughnut",options:{responsive:!0,plugins:{legend:{position:"bottom"},title:{display:!1,text:"HTTP Response Codes"}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchAuditBy("response_code",s.data.labels[e])}}},data:{datasets:[{label:"",data:[20,10],backgroundColor:["rgb(100, 99, 200)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)"]}],labels:[]}}),this.requestMethodChart=new Chart(this.$refs.requestMethodChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchAuditBy("request_method",s.data.labels[e])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)"],hoverOffset:4}]}}),this.componentUseChart=new Chart(this.$refs.componentUseChart.getContext("2d"),{type:"pie",options:{responsive:!0,plugins:{legend:{position:"xxx"},title:{display:!1,text:"Components"}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchAuditBy("component",s.data.labels[e])}}},data:{datasets:[{data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)","rgb(100, 205, 250)","rgb(120, 205, 250)","rgb(140, 205, 250)","rgb(160, 205, 250)"],hoverOffset:4}]}}),this.longDurationChart=new Chart(this.$refs.longDurationChart.getContext("2d"),{type:"bar",options:{responsive:!0,indexAxis:"y",maintainAspectRatio:!1,plugins:{legend:{title:{display:!1,text:"Long Duration"}}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchAuditBy("path",s.data.labels[e])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)","rgb(100, 205, 250)","rgb(120, 205, 250)","rgb(140, 205, 250)","rgb(160, 205, 250)"],hoverOffset:4}]}})):console.warn("Charts are not ready yet. Initialization delayed.")}}},window.PageWallet={template:"#page-wallet",data:()=>({parse:{show:!1,invoice:null,lnurlpay:null,lnurlauth:null,sending:!1,decoding:!1,decodeId:0,data:{request:"",amount:0,comment:"",memo:"",internalMemo:null,unit:"sat"},paymentChecker:null,copy:{show:!1},camera:{show:!1,camera:"auto"}},receive:{show:!1,status:"pending",paymentReq:null,paymentHash:null,amountMsat:null,minMax:[0,21e14],lnurl:null,units:[],unit:"sat",fiatProvider:"",data:{amount:null,memo:"",internalMemo:null,payment_hash:null}},update:{name:null,currency:null},hasNfc:!1,nfcReaderAbortController:null,formattedFiatAmount:0,totalBreakdown:{show:!1,loading:!1,rows:[],selectedTypes:["bitcoin","fiat"],selectedTags:[]},paymentFilter:{"status[ne]":"failed"},chartConfig:Quasar.LocalStorage.getItem("lnbits.wallets.chartConfig")||{showPaymentInOutChart:!0,showBalanceChart:!0,showBalanceInOutChart:!0}}),computed:{isFiatWallet(){return"fiat"===this.g.wallet.walletType},isCashPayment(){return this.isFiatWallet&&"cash"===this.receive.fiatProvider},bolt12AmountMissing(){return!(!this.parse.invoice||!this.parse.invoice.isBolt12Offer||Number(this.parse.data.amount)>0)},canPay(){return!!this.parse.invoice&&(this.parse.invoice.expired?(Quasar.Notify.create({message:"Invoice has expired",color:"negative"}),!1):this.parse.invoice.isBolt12Offer?!!this.bolt12AmountMissing||Number(this.parse.data.amount)<=this.g.wallet.sat:this.parse.invoice.sat<=this.g.wallet.sat)},lnurlpayInfo(){const e=this.parse.lnurlpay;if(!e)return{};const t={domain:e.callback.split("/")[2],fixed:e.minSendable===e.maxSendable};try{JSON.parse(e.metadata).forEach(([e,s])=>{"text/plain"===e?t.description=s:"image/png;base64"===e||"image/jpeg;base64"===e?t.image=`data:${e},${s}`:"text/identifier"!==e&&"text/email"!==e||(t.targetUser=s)})}catch{}return t},formattedAmount(){return this.isFiatWallet?LNbits.utils.formatCurrency(this.receive.data.amount,this.receive.unit):"sat"==this.receive.unit&&this.g.isSatsDenomination?LNbits.utils.formatMsat(this.receive.amountMsat)+" sat":LNbits.utils.formatCurrency(Number(this.receive.data.amount).toFixed(2),this.g.isSatsDenomination?this.receive.unit:this.g.denomination)},formattedSatAmount(){return LNbits.utils.formatMsat(this.receive.amountMsat)+" sat"},totalBreakdownTags(){const e=this.totalBreakdown.rows.map(e=>e.tag||null);return[...new Set(e)].sort((e,t)=>this.totalBreakdownTagLabel(e).localeCompare(this.totalBreakdownTagLabel(t)))},hasFiatTotalBreakdown(){return this.totalBreakdown.rows.some(e=>e.is_fiat)},selectedTotalBreakdownRows(){return this.totalBreakdown.rows.filter(e=>{const t=e.is_fiat?"fiat":"bitcoin";return this.totalBreakdown.selectedTypes.includes(t)&&this.totalBreakdown.selectedTags.includes(this.totalBreakdownTagKey(e.tag))})},selectedTotalBreakdownMsat(){return this.selectedTotalBreakdownRows.reduce((e,t)=>e+t.total,0)},selectedTotalBreakdownSat(){return Math.round(this.selectedTotalBreakdownMsat/1e3)},selectedTotalBreakdownCount(){return this.selectedTotalBreakdownRows.reduce((e,t)=>e+t.payments_count,0)},formattedTotalBreakdown(){return this.utils.formatBalance(this.selectedTotalBreakdownSat,this.g.denomination)},formattedTotalBreakdownFiat(){if(!this.g.fiatTracking)return null;const e=this.selectedTotalBreakdownSat/1e8*this.g.exchangeRate;return LNbits.utils.formatCurrency(e,this.g.wallet.currency)},primaryTotalBreakdownValue(){return this.g.isFiatPriority&&this.g.fiatTracking&&this.formattedTotalBreakdownFiat||this.formattedTotalBreakdown},secondaryTotalBreakdownValue(){return this.g.fiatTracking?this.g.isFiatPriority?this.formattedTotalBreakdown:this.formattedTotalBreakdownFiat:null}},methods:{showWalletTotalBreakdown(){this.totalBreakdown.show=!0,this.totalBreakdown.rows.length||this.fetchTotalBreakdown()},fetchTotalBreakdown(){this.totalBreakdown.loading=!0,LNbits.api.getPaymentTotalBreakdown(this.g.wallet).then(e=>{this.totalBreakdown.rows=e.data,this.totalBreakdown.selectedTypes=["bitcoin","fiat"],this.totalBreakdown.selectedTags=this.totalBreakdownTags.map(this.totalBreakdownTagKey),this.totalBreakdown.loading=!1}).catch(e=>{this.totalBreakdown.loading=!1,LNbits.utils.notifyApiError(e)})},totalBreakdownTagLabel:e=>e||"No tag",totalBreakdownTagKey:e=>e||"__untagged__",totalBreakdownTagCount(e){return this.totalBreakdown.rows.filter(t=>(t.tag||null)===e).reduce((e,t)=>e+t.payments_count,0)},totalBreakdownTagMsat(e){return this.totalBreakdown.rows.filter(t=>(t.tag||null)===e).reduce((e,t)=>e+t.total,0)},formatTotalBreakdownMsat(e){return this.utils.formatBalance(Math.round(e/1e3),this.g.denomination)},handleSendLnurl(e){this.parse.data.request=e,this.parse.show=!0,this.lnurlScan()},msatoshiFormat:e=>LNbits.utils.formatSat(e/1e3),showReceiveDialog(){this.receive.show=!0,this.receive.status="pending",this.receive.paymentReq=null,this.receive.paymentHash=null,this.receive.fiatPaymentReq=null,this.receive.fiatProvider=this.isFiatWallet?"cash":"",this.receive.data.amount=null,this.receive.data.memo=null,this.receive.data.internalMemo=null,this.receive.data.payment_hash=null,this.receive.units=[...this.isFiatWallet?[]:["sat"],...this.g.allowedCurrencies.length>0?this.g.allowedCurrencies:this.g.currencies],this.receive.unit=this.g.isFiatPriority&&this.g.wallet.currency||"sat",this.isFiatWallet&&(this.receive.unit=this.receive.units.includes(this.g.wallet.currency)?this.g.wallet.currency:this.receive.units[0]),this.receive.minMax=[0,21e14],this.receive.lnurl=null,this.receive.lnurlWithdraw=null},onReceiveDialogHide(){this.hasNfc&&this.nfcReaderAbortController?.abort()},showParseDialog(){this.parse.show=!0,this.parse.invoice=null,this.parse.lnurlpay=null,this.parse.lnurlauth=null,this.parse.copy.show=window.isSecureContext&&void 0!==navigator.clipboard?.readText,this.parse.data.request="",this.parse.data.comment="",this.parse.data.amount=0,this.parse.data.internalMemo=null,this.parse.data.memo="",this.parse.sending=!1,this.parse.data.paymentChecker=null,this.parse.camera.show=!1},closeParseDialog(){this.parse.decodeId++,this.parse.decoding=!1,setTimeout(()=>{clearInterval(this.parse.paymentChecker)},1e4)},handleBalanceUpdate(e){this.g.wallet.sat=this.g.wallet.sat+e},createInvoice(){if("loading"===this.receive.status)return;this.receive.status="loading",this.isFiatWallet||this.g.isSatsDenomination||(this.receive.data.amount=100*this.receive.data.amount);const e=this.isCashPayment;(e?LNbits.api.request("POST","/api/v1/fiat/cash",this.g.wallet.adminkey,{amount:this.receive.data.amount,unit:this.receive.unit,memo:this.receive.data.memo,internal_memo:this.receive.data.internalMemo}):LNbits.api.createInvoice(this.g.wallet,this.receive.data.amount,this.receive.data.memo,this.receive.unit,this.receive.lnurlWithdraw,this.receive.fiatProvider,this.receive.data.internalMemo,this.receive.data.payment_hash)).then(t=>{if(this.g.updatePayments=!this.g.updatePayments,this.receive.status="success",e)return this.receive.show=!1,void Quasar.Notify.create({type:"positive",message:"Cash payment validated."});if(this.receive.paymentReq=t.data.bolt11,this.receive.fiatPaymentReq=t.data.extra?.fiat_payment_request,this.receive.amountMsat=t.data.amount,this.receive.paymentHash=t.data.payment_hash,this.isFiatWallet||this.receive.lnurl||this.readNfcTag(),this.receive.lnurl&&null!==t.data.extra?.lnurl_response){!1===t.data.extra.lnurl_response&&(t.data.extra.lnurl_response="Unable to connect");const e=this.receive.lnurl.callback.split("/")[2];if("string"==typeof t.data.extra.lnurl_response)return void Quasar.Notify.create({timeout:5e3,type:"warning",message:`${e} lnurl-withdraw call failed.`,caption:t.data.extra.lnurl_response});!0===t.data.extra.lnurl_response&&Quasar.Notify.create({timeout:3e3,message:`Invoice sent to ${e}!`,spinner:!0})}}).catch(e=>{LNbits.utils.notifyApiError(e),this.receive.status="pending"})},lnurlScan(){LNbits.api.request("POST","/api/v1/lnurlscan",this.g.wallet.adminkey,{lnurl:this.parse.data.request}).then(e=>{const t=e.data;if("ERROR"!==t.status){if("payRequest"===t.tag)this.parse.lnurlpay=Object.freeze(t),this.parse.data.amount=t.minSendable/1e3,this.receive.units=["sats",...this.g.allowedCurrencies.length>0?this.g.allowedCurrencies:this.g.currencies];else if("login"===t.tag)this.parse.lnurlauth=Object.freeze(t);else if("withdrawRequest"===t.tag){this.parse.show=!1,this.receive.show=!0,this.receive.lnurlWithdraw=Object.freeze(t),this.receive.status="pending",this.receive.paymentReq=null,this.receive.paymentHash=null,this.receive.data.amount=t.maxWithdrawable/1e3,this.receive.data.memo=t.defaultDescription,this.receive.minMax=[t.minWithdrawable/1e3,t.maxWithdrawable/1e3];const e=t.callback.split("/")[2];this.receive.lnurl={domain:e,callback:t.callback,fixed:t.fixed}}}else Quasar.Notify.create({timeout:5e3,type:"warning",message:"lnurl scan failed.",caption:t.reason})}).catch(e=>{LNbits.utils.notifyApiError(e)})},decodeQR(e){this.parse.data.request=e,this.decodeRequest(),this.parse.camera.show=!1},isLnurl:e=>e.toLowerCase().startsWith("lnurl1")||e.startsWith("lnurlp://")||e.startsWith("lnurlw://")||e.startsWith("lnurlauth://")||e.match(/[\w.+-~_]+@[\w.+-~_]/),isBolt12Offer:e=>(e||"").trim().toLowerCase().startsWith("lno1"),async decodeRequest(){if(this.parse.decoding)return;this.parse.show=!0,this.parse.data.request=this.parse.data.request.trim();const e=this.parse.data.request.toLowerCase();if(e.startsWith("lightning:")?(this.parse.data.request=this.parse.data.request.slice(10),this.parse.data.request.startsWith("//")&&(this.parse.data.request=this.parse.data.request.slice(2))):e.startsWith("lnurl:")?this.parse.data.request=this.parse.data.request.slice(6):e.includes("lightning=lnurl1")&&(this.parse.data.request=this.parse.data.request.split("lightning=")[1].split("&")[0]),this.isLnurl(this.parse.data.request))return void this.lnurlScan();if(this.isBolt12Offer(this.parse.data.request)){const e=this.parse.data.request.trim().split("?")[0].split("#")[0];this.parse.data.request=e,this.parse.data.amount=0,this.parse.invoice=null,this.parse.decoding=!0;const t=++this.parse.decodeId;try{const{data:s}=await LNbits.api.request("post","/api/v1/payments/decode",null,{data:e});if(t!==this.parse.decodeId||!this.parse.show)return;const i=null==s.currency&&Number.isSafeInteger(s.amount)&&s.amount>0&&s.amount%1e3==0?s.amount/1e3:0;this.parse.data.request=s.offer,this.parse.data.amount=i,this.parse.invoice=Object.freeze({msat:null==s.currency?s.amount:null,sat:i,fsat:"offer",bolt11:s.offer,description:s.description,hash:null,isBolt12Offer:!0,expired:!1})}catch(e){t===this.parse.decodeId&&this.parse.show&&Quasar.Notify.create({type:"warning",message:e.response?.data?.message||e.message})}finally{t===this.parse.decodeId&&(this.parse.decoding=!1)}return}let t;this.parse.data.request.toLowerCase().includes("lightning")&&(this.parse.data.request=this.parse.data.request.split("lightning=")[1],this.parse.data.request.includes("&")&&(this.parse.data.request=this.parse.data.request.split("&")[0]));try{t=decode(this.parse.data.request)}catch(e){return Quasar.Notify.create({timeout:3e3,type:"warning",message:e+".",caption:"400 BAD REQUEST"}),void(this.parse.show=!1)}let s={msat:t.human_readable_part.amount,sat:t.human_readable_part.amount/1e3,fsat:LNbits.utils.formatSat(t.human_readable_part.amount/1e3),bolt11:this.parse.data.request};_.each(t.data.tags,e=>{if(_.isObject(e)&&_.has(e,"description"))if("payment_hash"===e.description)s.hash=e.value;else if("description"===e.description)s.description=e.value;else if("expiry"===e.description){const i=new Date(1e3*(t.data.time_stamp+e.value)),a=new Date(1e3*t.data.time_stamp);s.expireDate=Quasar.date.formatDate(i,"YYYY-MM-DDTHH:mm:ss.SSSZ"),s.createdDate=Quasar.date.formatDate(a,"YYYY-MM-DDTHH:mm:ss.SSSZ"),s.expireDateFrom=moment.utc(i).local().fromNow(),s.createdDateFrom=moment.utc(a).local().fromNow(),s.expired=!1}}),this.g.wallet.currency&&(s.fiatAmount=LNbits.utils.formatCurrency((s.sat/1e8*this.g.exchangeRate).toFixed(2),this.g.wallet.currency)),this.parse.invoice=Object.freeze(s)},payInvoice(){if(this.parse.sending)return;if(this.parse.invoice?.isBolt12Offer&&!(Number(this.parse.data.amount)>0))return;this.parse.sending=!0;const e=Quasar.Notify.create({timeout:0,message:this.$t("payment_processing")}),t=this.parse.invoice.isBolt12Offer?this.parse.data.amount:null;LNbits.api.payInvoice(this.g.wallet,this.parse.data.request,this.parse.data.internalMemo,t,this.parse.invoice.isBolt12Offer?this.parse.data.memo:null).then(t=>{this.parse.sending=!1,e(),this.g.updatePayments=!this.g.updatePayments,this.parse.show=!1,"success"==t.data.status&&Quasar.Notify.create({type:"positive",message:this.$t("payment_successful")}),"pending"==t.data.status&&Quasar.Notify.create({type:"info",message:this.$t("payment_pending")})}).catch(t=>{this.parse.sending=!1,e(),LNbits.utils.notifyApiError(t),this.g.updatePayments=!this.g.updatePayments})},payLnurl(){this.parse.sending||(this.parse.sending=!0,LNbits.api.request("post","/api/v1/payments/lnurl",this.g.wallet.adminkey,{res:this.parse.lnurlpay,lnurl:this.parse.data.request,unit:this.parse.data.unit,amount:1e3*this.parse.data.amount,comment:this.parse.data.comment,internalMemo:this.parse.data.internalMemo}).then(e=>{if(this.parse.sending=!1,this.parse.show=!1,e.data.extra.success_action){const t=JSON.parse(e.data.extra.success_action);switch(t.tag){case"url":Quasar.Notify.create({message:t.url,caption:t.description,html:!1,type:"positive",timeout:0,closeBtn:!0,actions:[{label:"Open link",color:"white",handler:()=>this.utils.openUrlInNewTab(t.url)}]});break;case"message":Quasar.Notify.create({message:t.message,type:"positive",timeout:0,closeBtn:!0});break;case"aes":this.utils.decryptLnurlPayAES(t,e.data.preimage).then(e=>{Quasar.Notify.create({message:e,caption:t.description,html:!1,type:"positive",timeout:0,closeBtn:!0})}).catch(e=>{Quasar.Notify.create({message:t.description||"Payment successful.",caption:"Could not decrypt success action.",html:!1,type:"warning",timeout:0,closeBtn:!0})})}}}).catch(e=>{this.parse.sending=!1,LNbits.utils.notifyApiError(e)}))},authLnurl(){const e=Quasar.Notify.create({timeout:10,message:"Performing authentication..."});LNbits.api.request("post","/api/v1/lnurlauth",wallet.adminkey,this.parse.lnurlauth).then(t=>{e(),Quasar.Notify.create({message:"Authentication successful.",type:"positive",timeout:3500}),this.parse.show=!1}).catch(e=>{e.response.data.reason?Quasar.Notify.create({message:`Authentication failed. ${this.parse.lnurlauth.callback} says:`,caption:e.response.data.reason,type:"warning",timeout:5e3}):LNbits.utils.notifyApiError(e)})},updateWallet(e){LNbits.api.request("PATCH","/api/v1/wallet",this.g.wallet.adminkey,e).then(e=>{const t={...e.data};t.lightning_address&&(t.lightningAddress=t.lightning_address,t.lightningAddressFull=`${t.lightning_address}@${window.location.host}`),this.g.wallet={...this.g.wallet,...t};const s=this.g.user.wallets.findIndex(t=>t.id===e.data.id);-1!==s&&(this.g.user.wallets[s]={...this.g.user.wallets[s],...t}),Quasar.Notify.create({message:"Wallet updated.",type:"positive",timeout:3500})}).catch(e=>{LNbits.utils.notifyApiError(e)})},pasteToTextArea(){this.$refs.textArea.focus(),navigator.clipboard.readText().then(e=>{this.parse.data.request=e.trim()})},readNfcTag(){try{if("undefined"==typeof NDEFReader)return void console.debug("NFC not supported on this device or browser.");const e=new NDEFReader;this.nfcReaderAbortController=new AbortController,this.nfcReaderAbortController.signal.onabort=e=>{console.debug("All NFC Read operations have been aborted.")},this.hasNfc=!0;const t=Quasar.Notify.create({message:"Tap your NFC tag to pay this invoice with LNURLw."});return e.scan({signal:this.nfcReaderAbortController.signal}).then(()=>{e.onreadingerror=()=>{Quasar.Notify.create({type:"negative",message:"There was an error reading this NFC tag."})},e.onreading=({message:e})=>{const s=new TextDecoder("utf-8"),i=e.records.find(e=>-1!==s.decode(e.data).toUpperCase().indexOf("LNURLW"));if(i){t(),Quasar.Notify.create({type:"positive",message:"NFC tag read successfully."});const e=s.decode(i.data);this.payInvoiceWithNfc(e)}else Quasar.Notify.create({type:"warning",message:"NFC tag does not have LNURLw record."})}})}catch(e){Quasar.Notify.create({type:"negative",message:e?e.toString():"An unexpected error has occurred."})}},payInvoiceWithNfc(e){const t=Quasar.Notify.create({timeout:0,spinner:!0,message:this.$t("payment_processing")});LNbits.api.request("POST",`/api/v1/payments/${this.receive.paymentReq}/pay-with-nfc`,this.g.wallet.adminkey,{lnurl_w:e}).then(e=>{t(),e.data.success?Quasar.Notify.create({type:"positive",message:"Payment successful"}):Quasar.Notify.create({type:"negative",message:e.data.detail||"Payment failed"})}).catch(e=>{t(),LNbits.utils.notifyApiError(e)})}},created(){const e=new URLSearchParams(window.location.search),t=this.g.user.wallets.find(e=>e.id===this.$route.params.id);t?(this.g.wallet=t,this.g.lastActiveWallet=t.id,this.$q.localStorage.setItem("lnbits.lastActiveWallet",t.id),this.$router.replace(`/wallet/${t.id}`).then(()=>{(e.has("lightning")||e.has("lnurl"))&&(this.parse.data.request=e.get("lightning")||e.get("lnurl"),this.decodeRequest(),this.parse.show=!0)})):(this.g.errorCode=404,this.g.errorMessage="Wallet not found.",this.$router.push("/error"))},watch:{"g.updatePaymentsHash"(){this.receive.show=!1},"g.updatePayments"(){this.parse.show=!1,this.g.wallet.currency&&this.$q.localStorage.getItem("lnbits.exchangeRate."+this.g.wallet.currency)&&(this.g.exchangeRate=this.$q.localStorage.getItem("lnbits.exchangeRate."+this.g.wallet.currency),this.g.fiatBalance=this.g.exchangeRate/1e8*this.g.wallet.sat)},"g.wallet"(){this.g.wallet.currency?(this.g.fiatTracking=!0,this.g.fiatBalance=this.g.exchangeRate/1e8*this.g.wallet.sat):(this.g.fiatBalance=0,this.g.fiatTracking=!1)},"g.isFiatPriority"(){this.receive.unit=this.g.isFiatPriority?this.g.wallet.currency:"sat"},"g.fiatBalance"(){this.formattedFiatAmount=LNbits.utils.formatCurrency(this.g.fiatBalance.toFixed(2),this.g.wallet.currency)},"g.exchangeRate"(){this.g.fiatTracking&&this.g.wallet.currency&&(this.g.fiatBalance=this.g.exchangeRate/1e8*this.g.wallet.sat)}}},window.PageWallets={template:"#page-wallets",data:()=>({user:null,tab:"wallets",wallets:[],addWalletDialog:{show:!1},walletsTable:{columns:[{name:"name",align:"left",label:"Name",field:"name",sortable:!0},{name:"currency",align:"center",label:"Currency",field:"currency",sortable:!0},{name:"updated_at",align:"right",label:"Last Updated",field:"updated_at",sortable:!0}],pagination:{sortBy:"updated_at",rowsPerPage:12,page:1,descending:!0,rowsNumber:10},search:"",hideEmpty:!0,loading:!1}}),watch:{"walletsTable.search":{handler(){const e={};this.walletsTable.search&&(e.search=this.walletsTable.search),this.getUserWallets()}}},methods:{async getUserWallets(e){try{this.walletsTable.loading=!0;const t=LNbits.utils.prepareFilterQuery(this.walletsTable,e),{data:s}=await LNbits.api.request("GET",`/api/v1/wallet/paginated?${t}`,null);this.wallets=s.data,this.walletsTable.pagination.rowsNumber=s.total}catch(e){LNbits.utils.notifyApiError(e)}finally{this.walletsTable.loading=!1}},goToWallet(e){this.$router.push({path:"/wallet",query:{wal:e}})},formattedFiatAmount:(e,t)=>LNbits.utils.formatCurrency(Number(e).toFixed(2),t),formattedSatAmount:e=>LNbits.utils.formatMsat(e)+" sat"},async created(){await this.getUserWallets()}},window.PageUsers={template:"#page-users",data(){return{paymentsWallet:{},cancel:{},users:[],wallets:[],searchData:{user:"",username:"",email:"",pubkey:""},paymentPage:{show:!1},activeWallet:{userId:null,show:!1},activeUser:{data:null,showUserId:!1,show:!1},createWalletDialog:{data:{},show:!1},lightningAddressDialog:{wallet:null,lightningAddress:"",show:!1},walletTable:{columns:[{name:"name",align:"left",label:"Name",field:"name"},{name:"id",align:"left",label:"Wallet Id",field:"id"},{name:"currency",align:"left",label:"Currency",field:"currency"},{name:"balance_msat",align:"left",label:"Balance",field:"balance_msat"}],pagination:{sortBy:"name",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},usersTable:{columns:[{name:"activated",align:"left",label:this.$t("activated"),field:"activated",sortable:!1},{name:"wallet_id",align:"left",label:"Wallets",field:"wallet_id",sortable:!1},{name:"id",align:"left",label:"User Id",field:"id",sortable:!1},{name:"username",align:"left",label:"Username",field:"username",sortable:!1},{name:"email",align:"left",label:"Email",field:"email",sortable:!1},{name:"pubkey",align:"left",label:"Public Key",field:"pubkey",sortable:!1},{name:"balance_msat",align:"left",label:"Balance",field:"balance_msat",sortable:!1},{name:"transaction_count",align:"left",label:"Payments",field:"transaction_count",sortable:!1},{name:"last_payment",align:"left",label:"Last Payment",field:"last_payment",sortable:!1}],pagination:{sortBy:"created_at",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},sortFields:[{name:"id",label:"User ID"},{name:"username",label:"Username"},{name:"email",label:"Email"},{name:"pubkey",label:"Public Key"},{name:"created_at",label:"Creation Date"},{name:"updated_at",label:"Last Updated"}],search:null,hideEmpty:!0,loading:!1}}},watch:{"usersTable.hideEmpty":function(e,t){this.usersTable.filter=e?{"transaction_count[gt]":0}:{},this.fetchUsers()}},created(){this.fetchUsers()},computed:{lightningAddressSuffix:()=>`@${window.location.host}`},methods:{formatSat:e=>LNbits.utils.formatSat(Math.floor(e/1e3)),backToUsersPage(){this.activeUser.show=!1,this.paymentPage.show=!1,this.activeWallet.show=!1,this.fetchUsers()},handleBalanceUpdate(){this.fetchWallets(this.activeWallet.userId)},resetPassword(e){return LNbits.api.request("PUT",`/users/api/v1/user/${e}/reset_password`).then(e=>{LNbits.utils.confirmDialog(this.$t("reset_key_generated")+" "+this.$t("reset_key_copy")).onOk(()=>{const t=window.location.origin+"?reset_key="+e.data;this.utils.copyText(t)})}).catch(LNbits.utils.notifyApiError)},sortByColumn(e){this.usersTable.pagination.sortBy===e?this.usersTable.pagination.descending=!this.usersTable.pagination.descending:(this.usersTable.pagination.sortBy=e,this.usersTable.pagination.descending=!1),this.fetchUsers()},createUser(){LNbits.api.request("POST","/users/api/v1/user",null,this.activeUser.data).then(e=>{Quasar.Notify.create({type:"positive",message:"User created!",icon:null}),this.activeUser.setPassword=!0,this.activeUser.data=e.data,this.fetchUsers()}).catch(LNbits.utils.notifyApiError)},updateUser(){LNbits.api.request("PUT",`/users/api/v1/user/${this.activeUser.data.id}`,null,this.activeUser.data).then(()=>{Quasar.Notify.create({type:"positive",message:"User updated!",icon:null}),this.activeUser.data=null,this.activeUser.show=!1,this.fetchUsers()}).catch(LNbits.utils.notifyApiError)},createWallet(){const e=this.activeWallet.userId;e?LNbits.api.request("POST",`/users/api/v1/user/${e}/wallet`,null,this.createWalletDialog.data).then(()=>{this.fetchWallets(e),Quasar.Notify.create({type:"positive",message:"Wallet created!"})}).catch(LNbits.utils.notifyApiError):Quasar.Notify.create({type:"warning",message:"No user selected!",icon:null})},deleteUser(e){LNbits.utils.confirmDialog("Are you sure you want to delete this user?").onOk(()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${e}`).then(()=>{this.fetchUsers(),Quasar.Notify.create({type:"positive",message:"User deleted!",icon:null}),this.activeUser.data=null,this.activeUser.show=!1}).catch(LNbits.utils.notifyApiError)})},undeleteUserWallet(e,t){LNbits.api.request("PUT",`/users/api/v1/user/${e}/wallet/${t}/undelete`).then(()=>{this.fetchWallets(e),Quasar.Notify.create({type:"positive",message:"Undeleted user wallet!",icon:null})}).catch(LNbits.utils.notifyApiError)},deleteUserWallet(e,t,s){const i=s?"Wallet is already deleted, are you sure you want to permanently delete this user wallet?":"Are you sure you want to delete this user wallet?";LNbits.utils.confirmDialog(i).onOk(()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${e}/wallet/${t}`).then(()=>{this.fetchWallets(e),Quasar.Notify.create({type:"positive",message:"User wallet deleted!",icon:null})}).catch(LNbits.utils.notifyApiError)})},deleteAllUserWallets(e){LNbits.utils.confirmDialog(this.$t("confirm_delete_all_wallets")).onOk(()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${e}/wallets`).then(t=>{Quasar.Notify.create({type:"positive",message:t.data.message,icon:null}),this.fetchWallets(e)}).catch(LNbits.utils.notifyApiError)})},copyWalletLink(e){const t=`${window.location.origin}/wallet?usr=${this.activeWallet.userId}&wal=${e}`;this.utils.copyText(t)},showLightningAddressDialog(e){this.lightningAddressDialog.wallet=e,this.lightningAddressDialog.lightningAddress=e.lightning_address||"",this.lightningAddressDialog.show=!0},saveLightningAddress(){const e=this.lightningAddressDialog.wallet;e&&LNbits.api.request("PUT",`/users/api/v1/user/${e.user}/wallet/${e.id}/lightning-address`,null,{lightning_address:this.lightningAddressDialog.lightningAddress}).then(t=>{Object.assign(e,t.data),this.lightningAddressDialog.show=!1,Quasar.Notify.create({type:"positive",message:this.$t("lightning_address_updated"),icon:null})}).catch(LNbits.utils.notifyApiError)},fetchUsers(e){this.relaxFilterForFields(["username","email"]);const t=LNbits.utils.prepareFilterQuery(this.usersTable,e);LNbits.api.request("GET",`/users/api/v1/user?${t}`).then(e=>{this.usersTable.loading=!1,this.usersTable.pagination.rowsNumber=e.data.total,this.users=e.data.data}).catch(LNbits.utils.notifyApiError)},fetchWallets(e){return LNbits.api.request("GET",`/users/api/v1/user/${e}/wallet`).then(t=>{this.wallets=t.data,this.activeWallet.userId=e,this.activeWallet.show=!0}).catch(LNbits.utils.notifyApiError)},relaxFilterForFields(e=[]){e.forEach(e=>{const t=this.usersTable?.filter?.[e];t&&this.usersTable.filter[e]&&(this.usersTable.filter[`${e}[like]`]=t,delete this.usersTable.filter[e])})},updateWallet(e){LNbits.api.request("PATCH","/api/v1/wallet",e.adminkey,{name:e.name}).then(()=>{e.editable=!1,Quasar.Notify.create({message:"Wallet name updated.",type:"positive",timeout:3500})}).catch(e=>{LNbits.utils.notifyApiError(e)})},toggleAdmin(e){LNbits.api.request("PUT",`/users/api/v1/user/${e}/admin`).then(()=>{this.fetchUsers(),Quasar.Notify.create({type:"positive",message:"Toggled admin!",icon:null})}).catch(LNbits.utils.notifyApiError)},toggleUserActivated(e){LNbits.api.request("PUT",`/users/api/v1/user/${e}/activate`).then(e=>{this.fetchUsers(),Quasar.Notify.create({type:"positive",message:e.data.message,icon:null})}).catch(LNbits.utils.notifyApiError)},async showAccountPage(e){if(this.activeUser.showPassword=!1,this.activeUser.showUserId=!1,this.activeUser.setPassword=!1,!e)return this.activeUser.data={extra:{}},void(this.activeUser.show=!0);try{const{data:t}=await LNbits.api.request("GET",`/users/api/v1/user/${e}`);this.activeUser.data=t,this.activeUser.show=!0}catch(e){console.warn(e),Quasar.Notify.create({type:"warning",message:"Failed to get user!"}),this.activeUser.show=!1}},async impersonateUser(e){try{await LNbits.api.impersonateUser(e),LNbits.utils.backupLocalStorage("impersonation",!0),this.$q.localStorage.setItem("lnbits.disclaimerShown",!0),window.location="/wallet"}catch(e){console.warn(e),Quasar.Notify.create({type:"warning",message:"Failed to impersonate user!"})}},async showWalletPayments(e){this.activeUser.show=!1,await this.fetchWallets(this.users[0].id),await this.showPayments(e)},showPayments(e){this.paymentsWallet=this.wallets.find(t=>t.id===e),this.paymentPage.show=!0},searchUserBy(e){const t=this.searchData[e];this.usersTable.filter={},t&&(this.usersTable.filter[e]=t),this.fetchUsers()},shortify:e=>(valueLength=(e||"").length,valueLength<=10?e:`${e.substring(0,5)}...${e.substring(valueLength-5,valueLength)}`)}},window.PageAccount={template:"#page-account",data(){return{untouchedUser:null,hasUsername:!1,showUserId:!1,themeOptions:[{name:"bitcoin",color:"deep-orange"},{name:"classic",color:"purple"},{name:"mint",color:"green"},{name:"autumn",color:"brown"},{name:"monochrome",color:"grey"},{name:"salvador",color:"blue-10"},{name:"freedom",color:"pink-13"},{name:"cyber",color:"light-green-9"},{name:"flamingo",color:"pink-3"}],defaultSiteCustomisation:{locale:"en"},reactionOptions:["None","confettiBothSides","confettiFireworks","confettiStars","confettiTop","lightningStrike"],borderOptions:["retro-border","hard-border","neon-border","no-border"],tab:"user",credentialsData:{show:!1,oldPassword:null,newPassword:null,newPasswordRepeat:null,username:null,pubkey:null},apiAcl:{showNewAclDialog:!1,showPasswordDialog:!1,showNewTokenDialog:!1,data:[],passwordGuardedFunction:null,newAclName:"",newTokenName:"",password:"",apiToken:null,selectedTokenId:null,columns:[{name:"Name",align:"left",label:this.$t("Name"),field:"Name",sortable:!1},{name:"path",align:"left",label:this.$t("path"),field:"path",sortable:!1},{name:"read",align:"left",label:this.$t("read"),field:"read",sortable:!1},{name:"write",align:"left",label:this.$t("write"),field:"write",sortable:!1}],pagination:{rowsPerPage:100,page:1}},selectedApiAcl:{id:null,name:null,endpoints:[],token_id_list:[],allRead:!1,allWrite:!1},assets:[],assetsTable:{loading:!1,columns:[{name:"name",align:"left",label:this.$t("Name"),field:"name",sortable:!0},{name:"created_at",align:"left",label:this.$t("created_at"),field:"created_at",sortable:!0}],pagination:{rowsPerPage:6,page:1}},assetsUploadToPublic:!1,notifications:{nostr:{identifier:""}},labels:[],labelsDialog:{show:!1,data:{name:"",description:"",color:"#000000"}},labelsTable:{loading:!1,columns:[{name:"actions",align:"left"},{name:"name",align:"left",label:this.$t("Name"),field:"name",sortable:!0},{name:"description",align:"left",label:this.$t("description"),field:"description"},{name:"color",align:"left",label:this.$t("color"),field:"color"}],pagination:{rowsPerPage:6,page:1}}}},watch:{tab(e){this.$router.push(`/account#${e}`)},$route(e){e.hash.length>1&&(this.tab=e.hash.replace("#",""))},"assetsTable.search":{handler(){const e={};this.assetsTable.search&&(e.search=this.assetsTable.search),this.getUserAssets()}}},computed:{accountNavigationItems(){return[{value:"user",label:this.$t("account_settings"),description:this.$t("account_settings_description"),icon:"person"},{value:"notifications",label:this.$t("notifications"),description:this.$t("account_notifications_description"),icon:"notifications"},{value:"theme",label:this.$t("look_and_feel"),description:this.$t("look_and_feel_description"),icon:"palette"},{value:"two_factor",label:this.$t("two_factor_auth_account"),description:this.$t("two_factor_description"),icon:"verified_user"},{value:"api_acls",label:this.$t("access_control_list"),description:this.$t("access_control_list_description"),icon:"lock"},{value:"assets",label:this.$t("assets"),description:this.$t("account_assets_description"),icon:"perm_media"},{value:"labels",label:this.$t("labels"),description:this.$t("account_labels_description"),icon:"local_offer"}]},activeAccountSection(){return this.accountNavigationItems.find(e=>e.value===this.tab)||this.accountNavigationItems[0]},isUserTouched(){return!_.isEqual(this.g.user,this.untouchedUser)},selectedApiToken(){return this.selectedApiAcl.token_id_list.find(e=>e.id===this.apiAcl.selectedTokenId)},expiryAt(){return this.selectedApiToken.expires_at?`${this.$t("expiry")}: ${LNbits.utils.formatTimestamp(this.selectedApiToken.expires_at)}`:""},tokenStatus(){if(this.selectedApiToken.expires_at){const e=new Date;let t="",s="positive";return new Date(1e3*this.selectedApiToken.expires_at)<e?(t=this.$t("acl_token_expired"),s="negative"):t=this.$t("acl_token_active"),{status:t,badgeColor:s}}return""}},methods:{changeLanguage(e){window.i18n.global.locale=e,this.$q.localStorage.set("lnbits.lang",e)},async updateAccount(){try{const{data:e}=await LNbits.api.request("PATCH","/api/v1/auth",null,{user_id:this.g.user.id,username:this.g.user.username,email:this.g.user.email,extra:this.g.user.extra});this.untouchedUser=JSON.parse(JSON.stringify(this.g.user)),this.hasUsername=!!e.username,Quasar.Notify.create({type:"positive",message:"Account updated."})}catch(e){LNbits.utils.notifyApiError(e)}},disableUpdatePassword(){return!this.credentialsData.newPassword||!this.credentialsData.newPasswordRepeat||this.credentialsData.newPassword!==this.credentialsData.newPasswordRepeat},async updatePassword(){if(this.credentialsData.username)try{const{data:e}=await LNbits.api.request("PUT","/api/v1/auth/password",null,{user_id:this.g.user.id,username:this.credentialsData.username,password_old:this.credentialsData.oldPassword,password:this.credentialsData.newPassword,password_repeat:this.credentialsData.newPasswordRepeat});this.untouchedUser=JSON.parse(JSON.stringify(e)),this.hasUsername=!!e.username,this.credentialsData.show=!1,Quasar.Notify.create({type:"positive",message:"Password updated."})}catch(e){LNbits.utils.notifyApiError(e)}else Quasar.Notify.create({type:"warning",message:"Please set a username."})},async updatePubkey(){try{const{data:e}=await LNbits.api.request("PUT","/api/v1/auth/pubkey",null,{user_id:this.g.user.id,pubkey:this.credentialsData.pubkey});this.untouchedUser=JSON.parse(JSON.stringify(e)),this.hasUsername=!!e.username,this.credentialsData.show=!1,this.$q.notify({type:"positive",message:"Public key updated."})}catch(e){LNbits.utils.notifyApiError(e)}},showUpdateCredentials(){this.credentialsData={show:!0,oldPassword:null,username:this.g.user.username,pubkey:this.g.user.pubkey,newPassword:null,newPasswordRepeat:null}},selectAccountSection(e){this.tab=e,"user"===e&&(this.credentialsData.show=!1)},newApiAclDialog(){this.apiAcl.newAclName=null,this.apiAcl.showNewAclDialog=!0},newTokenAclDialog(){this.apiAcl.newTokenName=null,this.apiAcl.newTokenExpiry=null,this.apiAcl.showNewTokenDialog=!0},handleApiACLSelected(e){this.selectedApiAcl={id:null,name:null,endpoints:[],token_id_list:[]},this.apiAcl.selectedTokenId=null,e&&setTimeout(()=>{const t=this.apiAcl.data.find(t=>t.id===e);this.selectedApiAcl&&(this.selectedApiAcl={...t},this.selectedApiAcl.allRead=this.selectedApiAcl.endpoints.every(e=>e.read),this.selectedApiAcl.allWrite=this.selectedApiAcl.endpoints.every(e=>e.write))})},handleAllEndpointsReadAccess(){this.selectedApiAcl.endpoints.forEach(e=>e.read=this.selectedApiAcl.allRead)},handleAllEndpointsWriteAccess(){this.selectedApiAcl.endpoints.forEach(e=>e.write=this.selectedApiAcl.allWrite)},async getApiACLs(){try{const{data:e}=await LNbits.api.request("GET","/api/v1/auth/acl",null);this.apiAcl.data=e.access_control_list}catch(e){LNbits.utils.notifyApiError(e)}},askPasswordAndRunFunction(e){this.apiAcl.passwordGuardedFunction=e,this.apiAcl.showPasswordDialog=!0},runPasswordGuardedFunction(){this.apiAcl.showPasswordDialog=!1;const e=this.apiAcl.passwordGuardedFunction;e&&this[e]()},async addApiACL(){if(this.apiAcl.newAclName){try{const{data:e}=await LNbits.api.request("PUT","/api/v1/auth/acl",null,{id:this.apiAcl.newAclName,name:this.apiAcl.newAclName,password:this.apiAcl.password});this.apiAcl.data=e.access_control_list;const t=this.apiAcl.data.find(e=>e.name===this.apiAcl.newAclName);this.handleApiACLSelected(t.id),this.apiAcl.showNewAclDialog=!1,this.$q.notify({type:"positive",message:"Access Control List created."})}catch(e){LNbits.utils.notifyApiError(e)}finally{this.apiAcl.name="",this.apiAcl.password=""}this.apiAcl.showNewAclDialog=!1}else this.$q.notify({type:"warning",message:"Name is required."})},async updateApiACLs(){try{const{data:e}=await LNbits.api.request("PUT","/api/v1/auth/acl",null,{id:this.g.user.id,password:this.apiAcl.password,...this.selectedApiAcl});this.apiAcl.data=e.access_control_list}catch(e){LNbits.utils.notifyApiError(e)}finally{this.apiAcl.password=""}},async deleteApiACL(){if(this.selectedApiAcl.id){try{await LNbits.api.request("DELETE","/api/v1/auth/acl",null,{id:this.selectedApiAcl.id,password:this.apiAcl.password}),this.$q.notify({type:"positive",message:"Access Control List deleted."})}catch(e){LNbits.utils.notifyApiError(e)}finally{this.apiAcl.password=""}this.apiAcl.data=this.apiAcl.data.filter(e=>e.id!==this.selectedApiAcl.id),this.handleApiACLSelected(this.apiAcl.data[0]?.id)}},async generateApiToken(){if(!this.selectedApiAcl.id)return;const e=new Date(this.apiAcl.newTokenExpiry)-new Date;try{const{data:t}=await LNbits.api.request("POST","/api/v1/auth/acl/token",null,{acl_id:this.selectedApiAcl.id,token_name:this.apiAcl.newTokenName,password:this.apiAcl.password,expiration_time_minutes:Math.trunc(e/6e4)});this.apiAcl.apiToken=t.api_token,this.apiAcl.selectedTokenId=t.id,Quasar.Notify.create({type:"positive",message:"Token Generated."}),await this.getApiACLs(),this.handleApiACLSelected(this.selectedApiAcl.id),this.apiAcl.showNewTokenDialog=!1}catch(e){LNbits.utils.notifyApiError(e)}finally{this.apiAcl.password=""}},async deleteToken(){if(this.apiAcl.selectedTokenId)try{await LNbits.api.request("DELETE","/api/v1/auth/acl/token",null,{id:this.apiAcl.selectedTokenId,acl_id:this.selectedApiAcl.id,password:this.apiAcl.password}),this.$q.notify({type:"positive",message:"Token deleted."}),this.selectedApiAcl.token_id_list=this.selectedApiAcl.token_id_list.filter(e=>e.id!==this.apiAcl.selectedTokenId),this.apiAcl.selectedTokenId=null}catch(e){LNbits.utils.notifyApiError(e)}finally{this.apiAcl.password=""}},async getUserAssets(e){try{this.assetsTable.loading=!0;const t=LNbits.utils.prepareFilterQuery(this.assetsTable,e),{data:s}=await LNbits.api.request("GET",`/api/v1/assets/paginated?${t}`,null);this.assets=s.data,this.assetsTable.pagination.rowsNumber=s.total}catch(e){LNbits.utils.notifyApiError(e)}finally{this.assetsTable.loading=!1}},onImageInput(e){const t=e.target.files[0];t&&this.uploadAsset(t),e.target.value=null},onBackgroundImageInput(e){const t=e.target.files[0];t&&this.uploadBackgroundImage(t),e.target.value=null},async uploadAsset(e,{isPublic:t=this.assetsUploadToPublic,notifySuccess:s=!0}={}){const i=new FormData;i.append("file",e);try{const{data:e}=await LNbits.api.request("POST",`/api/v1/assets?public_asset=${t}`,null,i,{headers:{"Content-Type":"multipart/form-data"}});return s&&this.$q.notify({type:"positive",message:"Upload successful!",icon:null}),await this.getUserAssets(),e}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async uploadBackgroundImage(e){const t=await this.uploadAsset(e,{isPublic:!1,notifySuccess:!1});if(!t)return;const s=`${window.location.origin}/api/v1/assets/${t.id}/thumbnail`;await this.siteCustomisationChanged({bgimageChoice:s})},async deleteAsset(e){LNbits.utils.confirmDialog("Are you sure you want to delete this asset?").onOk(async()=>{try{await LNbits.api.request("DELETE",`/api/v1/assets/${e.id}`,null),this.$q.notify({type:"positive",message:"Asset deleted."}),await this.getUserAssets()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}})},async toggleAssetPublicAccess(e){try{await LNbits.api.request("PUT",`/api/v1/assets/${e.id}`,null,{is_public:!e.is_public}),this.$q.notify({type:"positive",message:"Update successful!",icon:null}),await this.getUserAssets()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},copyAssetLinkToClipboard(e){const t=`${window.location.origin}/api/v1/assets/${e.id}/data`;this.utils.copyText(t)},addUserLabel(){if(!this.labelsDialog.data.name)return void this.$q.notify({type:"warning",message:"Name is required."});if(!this.labelsDialog.data.color)return void this.$q.notify({type:"warning",message:"Color is required."});this.g.user.extra.labels=this.g.user.extra.labels||[];if(!this.g.user.extra.labels.find(e=>e.name===this.labelsDialog.data.name))return this.g.user.extra.labels.unshift({...this.labelsDialog.data}),this.labelsDialog.show=!1,!0;this.$q.notify({type:"warning",message:"A label with this name already exists."})},openAddLabelDialog(){this.labelsDialog.data={name:"",description:"",color:"#000000"},this.labelsDialog.show=!0},openEditLabelDialog(e){this.labelsDialog.data={name:e.name,description:e.description,color:e.color},this.labelsDialog.show=!0},updateUserLabel(){const e=this.labelsDialog.data,t=JSON.parse(JSON.stringify(this.g.user.extra.labels));this.g.user.extra.labels=this.g.user.extra.labels.filter(t=>t.name!==e.name);this.addUserLabel()||(this.g.user.extra.labels=t),this.labelsDialog.show=!1},deleteUserLabel(e){LNbits.utils.confirmDialog("Are you sure you want to delete this label?").onOk(()=>{this.g.user.extra.labels=this.g.user.extra.labels.filter(t=>t.name!==e.name)})},async siteCustomisationChanged(e={}){try{Object.entries(e||{}).forEach(([e,t])=>{e in this.g&&(this.g[e]=t)}),await LNbits.api.updateUiCustomization(e),this.$q.notify({type:"positive",message:"UI Customization updated."})}catch(e){LNbits.utils.notifyApiError(e)}},resetThemeDefaults(){const e={themeChoice:this.g.settings.defaultTheme,borderChoice:this.g.settings.defaultBorder,gradientChoice:this.g.settings.defaultGradient,bgimageChoice:this.g.settings.defaultBgimage||"",reactionChoice:this.g.settings.defaultReaction,darkChoice:this.g.settings.defaultDark,cardRoundedChoice:this.g.settings.defaultCardRounded,cardGradientChoice:this.g.settings.defaultCardGradient,cardShadowChoice:this.g.settings.defaultCardShadow,burgerMenuChoice:this.g.settings.defaultBurgerMenuBackground};this.siteCustomisationChanged(e)}},async created(){this.untouchedUser=JSON.parse(JSON.stringify(this.g.user)),this.hasUsername=!!this.g.user.username,this.$route.hash.length>1&&(this.tab=this.$route.hash.replace("#","")),await this.getApiACLs(),await this.getUserAssets(),this.themeOptions=this.themeOptions.filter(e=>this.g.settings.themeOptions.includes(e.name))}},window.PageAdmin={template:"#page-admin",data:()=>({tab:"funding",settings:{},formData:{lnbits_exchange_rate_providers:[],lnbits_audit_exclude_paths:[],lnbits_audit_include_paths:[],lnbits_audit_http_response_codes:[]},isSuperUser:!1,needsRestart:!1,isSaving:!1,settingsLoaded:!1,settingsSearch:""}),watch:{tab(e){if(["wasm-runtime","wasm-limit-config"].includes(e)&&this.$route.path.startsWith("/admin/extensions/wasm"))return;const t=this.adminRouteForTab(e);this.$route.fullPath!==t&&this.$router.push(t)},$route(e){const t=this.adminTabFromRoute(e);this.tab!==t&&(this.tab=t)}},async created(){this.tab=this.adminTabFromRoute(this.$route),await this.getSettings()},computed:{checkChanges(){return this.settingsLoaded&&!_.isEqual(this.settings,this.formData)},settingsNavigation:()=>[{label:"settings_money",items:[{value:"funding",label:"funding",icon:"account_balance_wallet"},{value:"server",label:"payments",icon:"price_change"},{value:"exchange_providers",label:"exchanges",icon:"show_chart"},{value:"fiat_providers",label:"fiat_providers",icon:"credit_score"}]},{label:"settings_access",items:[{value:"security",label:"security",icon:"security"},{value:"users",label:"users",icon:"group"},{value:"two_factor",label:"two_factor_auth",icon:"verified_user"}]},{label:"settings_system",items:[{value:"extensions",label:"extensions",icon:"extension"},{value:"notifications",label:"notifications",icon:"notifications"},{value:"audit",label:"api_watch",icon:"playlist_add_check_circle"}]},{label:"settings_appearance",items:[{value:"assets-config",label:"assets",icon:"perm_media"},{value:"site_customisation",label:"site_customisation",icon:"palette"},{value:"blockexplorer",label:"block_explorer",icon:"travel_explore"}]}],settingsNavigationItems(){return this.settingsNavigation.flatMap(e=>e.items.map(t=>({...t,label:this.$t(t.label),group:this.$t(e.label)})))},settingsSearchIndex(){const e={funding:[this.$t("wallets_management"),this.$t("funding_sources"),this.$t("routing_fee_reserve_calculations"),this.$t("payment_timeouts"),this.$t("watchdog")],server:[this.$t("currency_settings"),this.$t("payments"),this.$t("lightning_addresses"),this.$t("wallet_limiter"),this.$t("service_fees")],exchange_providers:["LNbits Price Aggregator","Bitcoin Price History",this.$t("exchange_providers")],fiat_providers:[this.$t("fiat_providers"),this.$t("api"),this.$t("webhook"),this.$t("service_fees"),this.$t("amount_limits")],security:[this.$t("server_management"),this.$t("authentication"),"Nostr Auth","Google Auth","GitHub Auth","Keycloak Auth","OIDC Auth",this.$t("security_tools"),this.$t("ip_blocker"),this.$t("rate_limiter"),this.$t("callback"),this.$t("lnurl")],users:[this.$t("user_management"),this.$t("admin_users"),this.$t("allowed_users"),this.$t("allow_creation_user")],extensions:[this.$t("extension_sources"),"Wasm Extension",this.$t("admin_extensions"),this.$t("user_default_extensions"),this.$t("extension_builder_manifest_url"),this.$t("reviews_url")],notifications:[this.$t("notifications_configure"),this.$t("notifications_nostr_config"),this.$t("notifications_telegram_config"),this.$t("notifications_email_config"),this.$t("notifications")],audit:[this.$t("audit"),this.$t("audit_record_req"),this.$t("audit_http_methods_label"),this.$t("audit_paths_label")],"assets-config":["Assets","Thumbnails","Users"],site_customisation:[this.$t("ui_management"),this.$t("ui_custom_badge_title"),this.$t("ui_custom_image"),this.$t("themes"),this.$t("ad_space_section_title")],blockexplorer:[this.$t("block_explorer"),this.$t("electrum_compatible_server")]};return this.settingsNavigationItems.flatMap(t=>(e[t.value]||[t.label]).map(e=>({tab:t.value,category:t.label,section:e,icon:t.icon,searchText:`${t.group} ${t.label} ${e}`.toLowerCase()})))},filteredSettingsSearch(){const e=(this.settingsSearch||"").toLowerCase().split(/\s+/).filter(Boolean);return e.length?this.settingsSearchIndex.filter(t=>e.every(e=>t.searchText.includes(e))).slice(0,12):[]}},methods:{adminTabFromRoute:e=>e.path.startsWith("/admin/extensions/wasm/limits")?"wasm-limit-config":e.path.startsWith("/admin/extensions/wasm")?"wasm-runtime":e.hash.length>1?e.hash.replace("#",""):"funding",adminRouteForTab:e=>"wasm-runtime"===e?"/admin/extensions/wasm":"wasm-limit-config"===e?"/admin/extensions/wasm/limits":`/admin#${e}`,selectSettingsSearchResult(e){this.tab=e.tab,this.settingsSearch="",this.$nextTick(()=>{window.setTimeout(()=>{const t=[...document.querySelectorAll(".q-tab-panel--active h6, .q-tab-panel--active strong, .q-tab-panel--active .text-subtitle1")].find(t=>t.textContent.trim().toLowerCase().includes(e.section.toLowerCase()));t?.scrollIntoView({behavior:"smooth",block:"start"})},350)})},getDefaultSetting(e){LNbits.api.getDefaultSetting(e).then(t=>{this.formData[e]=t.data.default_value})},restartServer(){LNbits.api.request("GET","/admin/api/v1/restart/").then(e=>{this.$q.notify({type:"positive",message:"Success! Restarted Server",icon:null}),this.needsRestart=!1}).catch(LNbits.utils.notifyApiError)},async getSettings(){await LNbits.api.request("GET","/admin/api/v1/settings",this.g.user.wallets[0].adminkey).then(e=>{this.isSuperUser=e.data.is_super_user||!1,this.settings=e.data,this.formData={...this.settings},this.settingsLoaded=!0}).catch(LNbits.utils.notifyApiError)},updateSettings(){const e=_.omit(this.formData,["is_super_user","lnbits_allowed_funding_sources","touch"]);this.isSaving=!0,LNbits.api.request("PUT","/admin/api/v1/settings",this.g.user.wallets[0].adminkey,e).then(e=>{this.needsRestart=this.settings.lnbits_backend_wallet_class!==this.formData.lnbits_backend_wallet_class,this.settings=this.formData,this.formData=_.clone(this.settings),LNbits.api.getAuthUser().then(e=>{this.g.user=LNbits.map.user(e.data)}).catch(LNbits.utils.notifyApiError),Quasar.Notify.create({type:"positive",message:"Success! Settings changed! "+(this.needsRestart?"Restart required!":""),icon:null})}).catch(LNbits.utils.notifyApiError).finally(()=>{this.isSaving=!1})},deleteSettings(){LNbits.utils.confirmDialog("Are you sure you want to restore settings to default?").onOk(()=>{LNbits.api.request("DELETE","/admin/api/v1/settings").then(e=>{Quasar.Notify.create({type:"positive",message:"Success! Restored settings to defaults. Restarting...",icon:null}),this.$q.localStorage.clear()}).catch(LNbits.utils.notifyApiError)})},downloadBackup(){window.open("/admin/api/v1/backup","_blank")}}},window.app.component("lnbits-admin-funding-seed-backup",{props:["active","is-super-user","form-data","settings"],template:"#lnbits-admin-funding-seed-backup",data:()=>({dialog:{show:!1,step:1,seed:"",visible:!1,challenge:[],answers:{},error:"",confirmField:""}}),watch:{active(e){e&&this.openIfRequired()},"formData.lnbits_backend_wallet_class"(e,t){const s=this.seedBackupSource(e);t&&s&&this.formData[s.seedField]&&(this.formData[s.confirmField]=!1),this.openIfRequired()},"formData.boltz_mnemonic"(){this.formData.boltz_mnemonic_backup_confirmed=this.formData.boltz_mnemonic===this.settings.boltz_mnemonic&&this.settings.boltz_mnemonic_backup_confirmed,this.openIfRequired()},"formData.phoenixd_mnemonic"(){this.formData.phoenixd_mnemonic_backup_confirmed=this.formData.phoenixd_mnemonic===this.settings.phoenixd_mnemonic&&this.settings.phoenixd_mnemonic_backup_confirmed,this.openIfRequired()},"formData.spark_l2_mnemonic"(){this.formData.spark_l2_mnemonic_backup_confirmed=this.formData.spark_l2_mnemonic===this.settings.spark_l2_mnemonic&&this.settings.spark_l2_mnemonic_backup_confirmed,this.openIfRequired()}},computed:{seedWords(){return this.dialog.seed.split(/\s+/).filter(Boolean).map((e,t)=>({index:t,word:e}))}},created(){this.openIfRequired()},methods:{seedBackupSource(e=this.formData.lnbits_backend_wallet_class){return"BoltzWallet"===e?{seedField:"boltz_mnemonic",confirmField:"boltz_mnemonic_backup_confirmed"}:"PhoenixdWallet"===e?{seedField:"phoenixd_mnemonic",confirmField:"phoenixd_mnemonic_backup_confirmed"}:"SparkL2Wallet"===e?{seedField:"spark_l2_mnemonic",confirmField:"spark_l2_mnemonic_backup_confirmed"}:void 0},openIfRequired(){if(!this.active||!this.isSuperUser)return;const e=this.seedBackupSource();if(!e)return;const t=(this.formData[e.seedField]||"").trim(),s=this.formData[e.confirmField];!t||s||this.dialog.show||(this.dialog={show:!0,step:1,seed:t,visible:!1,challenge:[],answers:{},error:"",confirmField:e.confirmField})},prepareChallenge(){const e=this.dialog.seed.split(/\s+/).filter(Boolean),t=Math.min(4,e.length),s=_.shuffle([...Array(e.length).keys()]).slice(0,t);this.dialog.challenge=s.sort((e,t)=>e-t).map(t=>({index:t,word:e[t]})),this.dialog.answers={},this.dialog.error="",this.dialog.step=2},submitChallenge(){if(!this.dialog.challenge.every(({index:e,word:t})=>(this.dialog.answers[e]||"").trim().toLowerCase()===t.toLowerCase()))return void(this.dialog.error="One or more words are incorrect. Check your backup and try again.");const e=this.dialog.confirmField;LNbits.api.request("PATCH","/admin/api/v1/settings",this.g.user.wallets[0].adminkey,{[e]:!0}).then(()=>{this.formData[e]=!0,this.settings[e]=!0,this.dialog.show=!1,Quasar.Notify.create({type:"positive",message:"Seed backup confirmed",icon:"check"})}).catch(LNbits.utils.notifyApiError)}}}),window.app.component("lnbits-admin-funding",{props:["active","is-super-user","form-data","settings"],template:"#lnbits-admin-funding",data:()=>({auditData:[]}),created(){this.getAudit()},methods:{getAudit(){LNbits.api.request("GET","/admin/api/v1/audit",this.g.user.wallets[0].adminkey).then(e=>{this.auditData=e.data}).catch(LNbits.utils.notifyApiError)}}}),window.app.component("lnbits-admin-funding-sources",{template:"#lnbits-admin-funding-sources",props:["form-data","allowed-funding-sources"],methods:{getFundingSourceLabel(e){const t=this.rawFundingSources.find(t=>t[0]===e);return t?t[1]:e},showQRValue(e){this.qrValue=e,this.showQRDialog=!0}},computed:{fundingSources(){let e=[];for(const[t,s,i]of this.rawFundingSources){const s={};if(null!==i)for(let[e,t]of Object.entries(i))s[e]="string"==typeof t?{label:t,value:null}:t||{};e.push([t,s])}return new Map(e)},sortedAllowedFundingSources(){return this.allowedFundingSources.sort()}},data:()=>({hideInput:!0,showQRDialog:!1,qrValue:"",rawFundingSources:[["VoidWallet","Void Wallet",null],["FakeWallet","Fake Wallet",{fake_wallet_secret:"Secret",lnbits_denomination:'"sats" or 3 Letter Custom Denomination'}],["CLNRestWallet","Core Lightning Rest (plugin)",{clnrest_url:"Endpoint",clnrest_ca:"ca.pem",clnrest_cert:"server.pem",clnrest_readonly_rune:"Rune used for readonly requests",clnrest_invoice_rune:"Rune used for creating invoices",clnrest_pay_rune:"Rune used for paying invoices using pay",clnrest_renepay_rune:"Rune used for paying invoices using renepay",clnrest_last_pay_index:"Ignores any invoices paid prior to or including this index. 0 is equivalent to not specifying and negative value is invalid.",clnrest_nodeid:"Node id"}],["CoreLightningWallet","Core Lightning",{corelightning_rpc:"Endpoint",corelightning_pay_command:"Custom Pay Command"}],["CoreLightningRestWallet","Core Lightning Rest (legacy)",{corelightning_rest_url:"Endpoint",corelightning_rest_cert:"Certificate",corelightning_rest_macaroon:"Macaroon"}],["LndRestWallet","Lightning Network Daemon (LND Rest)",{lnd_rest_endpoint:"Endpoint",lnd_rest_cert:"Certificate",lnd_rest_macaroon:"Macaroon",lnd_rest_macaroon_encrypted:"Encrypted Macaroon",lnd_rest_route_hints:{advanced:!0,label:"Enable Route Hints"},lnd_rest_allow_self_payment:{advanced:!0,label:"Allow Self Payment"}}],["LndWallet","Lightning Network Daemon (LND)",{lnd_grpc_endpoint:"Endpoint",lnd_grpc_cert:"Certificate",lnd_grpc_port:"Port",lnd_grpc_macaroon:"GRPC Macaroon",lnd_grpc_invoice_macaroon:"GRPC Invoice Macaroon",lnd_grpc_admin_macaroon:"GRPC Admin Macaroon",lnd_grpc_macaroon_encrypted:"Encrypted Macaroon",lnd_grpc_allow_self_payment:{advanced:!0,label:"Allow Self Payment"}}],["LnTipsWallet","LN.Tips",{lntips_api_endpoint:"Endpoint",lntips_api_key:"API Key"}],["LNPayWallet","LN Pay",{lnpay_api_endpoint:"Endpoint",lnpay_api_key:"API Key",lnpay_wallet_key:"Wallet Key"}],["EclairWallet","Eclair (ACINQ)",{eclair_url:"URL",eclair_pass:"Password"}],["LNbitsWallet","LNbits",{lnbits_endpoint:"Endpoint",lnbits_key:"Admin Key"}],["BlinkWallet","Blink",{blink_api_endpoint:"Endpoint",blink_ws_endpoint:"WebSocket",blink_token:"Key",blink_send_without_probe:{advanced:!0,label:"Send payment if fee probe fails",hint:"If enabled (default), payments to destinations that cannot be probed (e.g. fedimints) are still sent. If disabled, such payments fail."}}],["AlbyWallet","Alby",{alby_api_endpoint:"Endpoint",alby_access_token:"Key"}],["BarkWallet","Bark",{bark_api_endpoint:{label:"Endpoint",value:"http://localhost:3000"},bark_api_token:"auth_token"}],["BoltzWallet","Boltz",{boltz_client_endpoint:{label:"Boltz client endpoint",value:"127.0.0.1:9002"},boltz_client_macaroon:{label:"Admin Macaroon path or hex",value:"/home/ubuntu/.boltz/macaroons/admin.macaroon"},boltz_client_cert:{label:"Certificate path or hex",value:"/home/ubuntu/.boltz/tls.cert"},boltz_mnemonic:{label:"Liquid seed phrase",hint:"Boltz will fetch once connected, but you can change later (can be opened in a liquid wallet) ",copy:!0,qrcode:!0},boltz_client_password:{label:"Wallet Password (optional)",advanced:!0}}],["ZBDWallet","ZBD",{zbd_api_endpoint:"Endpoint",zbd_api_key:"Key"}],["PhoenixdWallet","Phoenixd",{phoenixd_api_endpoint:"Endpoint",phoenixd_api_password:"Key",phoenixd_data_dir:{label:"Data Directory",hint:"Directory where phoenixd stores its data, including the seed phrase."},phoenixd_mnemonic:{label:"Phoenixd Seed Phrase",hint:"Only available if phoenixd data-dir is specified",readonly:!0,copy:!0,qrcode:!0}}],["OpenNodeWallet","OpenNode",{opennode_api_endpoint:"Endpoint",opennode_key:"Key"}],["SparkWallet","Spark",{spark_url:"Endpoint",spark_token:"Token"}],["SparkL2Wallet","Spark (L2)",{spark_l2_external_endpoint:{label:"External Sidecar Endpoint",hint:"Make sure to also specify the API key if your sidecar requires authentication.",value:""},spark_l2_mnemonic:{label:"External Sidecar Mnemonic",hint:"Mnemonic for the Spark wallet on the external sidecar. Required if the side car does not have its own mnemonic.",value:""},spark_l2_external_api_key:{label:"External Sidecar API Key",hint:"API key for authenticating with the external sidecar if it requires authentication.",value:""},spark_l2_network:{label:"Network",value:"MAINNET",hint:"The network to use for the Spark wallet.",advanced:!0},spark_l2_pay_wait_ms:{label:"Payment Wait Time (ms)",hint:"The time to wait for a payment to be processed before considering it failed.",advanced:!0},spark_l2_pay_poll_ms:{label:"Payment Poll Time (ms)",hint:"The time to wait between polling for payment status updates.",advanced:!0},spark_l2_stream_keepalive_ms:{label:"Stream Keepalive Time (ms)",hint:"The time to wait between sending keepalive messages to the Spark sidecar to keep the connection open.",advanced:!0}}],["NWCWallet","Nostr Wallet Connect",{nwc_pairing_url:"Pairing URL"}],["BreezSdkWallet","Breez SDK",{breez_api_key:"Breez API Key",breez_greenlight_seed:"Greenlight Seed",breez_greenlight_device_key:"Greenlight Device Key",breez_greenlight_device_cert:"Greenlight Device Cert",breez_greenlight_invite_code:"Greenlight Invite Code"}],["StrikeWallet","Strike (alpha)",{strike_api_endpoint:"API Endpoint",strike_api_key:"API Key"}],["BreezLiquidSdkWallet","Breez Liquid SDK",{breez_liquid_api_key:"Breez API Key (can be empty)",breez_liquid_seed:"Liquid seed phrase",breez_liquid_fee_offset_sat:"Offset amount in sats to increase fee limit"}]]})}),window.app.component("lnbits-admin-fiat-providers",{props:["form-data"],template:"#lnbits-admin-fiat-providers",data:()=>({formAddStripeUser:"",formAddPaypalUser:"",formAddSquareUser:"",formAddRevolutUser:"",creatingRevolutWebhook:!1,hideInputToggle:!0}),computed:{stripeWebhookUrl(){return this.formData?.stripe_payment_webhook_url||this.calculateWebhookUrl("stripe")},paypalWebhookUrl(){return this.formData?.paypal_payment_webhook_url||this.calculateWebhookUrl("paypal")},revolutWebhookUrl(){return this.formData?.revolut_payment_webhook_url||this.calculateWebhookUrl("revolut")}},watch:{formData:{handler(){this.syncWebhookUrls()},immediate:!0}},methods:{basePathFromLocation(){if("undefined"==typeof window)return"";const e=window.location.pathname.replace(/\/+$/,""),t=e.lastIndexOf("/admin");return(t>=0?e.slice(0,t):e||"")||""},calculateWebhookUrl(e){if("undefined"==typeof window)return"";const t=`${this.basePathFromLocation()}/api/v1/callback/${e}`.replace(/\/+/g,"/"),s=t.startsWith("/")?t:`/${t}`;return`${window.location.origin}${s}`},syncWebhookUrls(){this.maybeSetWebhookUrl("stripe_payment_webhook_url","stripe"),this.maybeSetWebhookUrl("paypal_payment_webhook_url","paypal"),this.maybeSetWebhookUrl("square_payment_webhook_url","square"),this.maybeSetWebhookUrl("revolut_payment_webhook_url","revolut")},maybeSetWebhookUrl(e,t){if(!this.formData)return;const s=this.calculateWebhookUrl(t),i=this.formData[e];(!i||i.includes("your-lnbits-domain-here.com"))&&s&&(this.formData[e]=s)},copyWebhookUrl(e){e&&this.copyText(e)},isClearnetWebhookUrl(e){let t;try{t=new URL(e)}catch(e){return!1}const s=t.hostname.toLowerCase();return!!["http:","https:"].includes(t.protocol)&&(!("localhost"===s||s.endsWith(".localhost")||s.endsWith(".local")||s.endsWith(".onion"))&&!(/^127\./.test(s)||/^10\./.test(s)||/^192\.168\./.test(s)||/^169\.254\./.test(s)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(s)||"0.0.0.0"===s||"::1"===s))},notifyRevolutWebhookWarning(e){Quasar.Notify.create({type:"warning",message:e,icon:null,closeBtn:!0})},addStripeAllowedUser(){const e=this.formAddStripeUser||"";e.length&&!this.formData.stripe_limits.allowed_users.includes(e)&&(this.formData.stripe_limits.allowed_users=[...this.formData.stripe_limits.allowed_users,e],this.formAddStripeUser="")},removeStripeAllowedUser(e){this.formData.stripe_limits.allowed_users=this.formData.stripe_limits.allowed_users.filter(t=>t!==e)},addPaypalAllowedUser(){const e=this.formAddPaypalUser||"";e.length&&!this.formData.paypal_limits.allowed_users.includes(e)&&(this.formData.paypal_limits.allowed_users=[...this.formData.paypal_limits.allowed_users,e],this.formAddPaypalUser="")},removePaypalAllowedUser(e){this.formData.paypal_limits.allowed_users=this.formData.paypal_limits.allowed_users.filter(t=>t!==e)},addSquareAllowedUser(){const e=this.formAddSquareUser||"";e.length&&!this.formData.square_limits.allowed_users.includes(e)&&(this.formData.square_limits.allowed_users=[...this.formData.square_limits.allowed_users,e],this.forWhy this scored 59/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.