Compare commits

...
66 Commits
Author SHA1 Message Date
Vlad Stan d4da96597e chore: project version bump 2024-05-22 12:04:56 +03:00
Vlad StanandGitHub 6a0b645316 hotfix: check for lnbits_site_description setting (#2527)
* fix: make `lnbits_site_description` optional again
2024-05-22 10:53:34 +02:00
dni ⚡andGitHub 35bb3cc94b fix: topup wallet was showing NaN (#2504)
* fix: topup wallet was showing NaN
2024-05-16 15:31:24 +02:00
Gonçalo ValérioandGitHub 7a6c3646fb Fix: Wrong expiration date in invoice details (#2506)
* invoices without the x tag, should be assumed to take 3600 seconds to expire

* update bolt11 package and use built in method to calculate the invoice expiry date

* fix linter errors
2024-05-16 13:48:58 +01:00
b84161c49d [chore] Update legend to demo (#2505)
* fix: update `legend.lnbits.com` to `demo.lnbits.com`
* Update docs/guide/admin_ui.md
* fix: docker image name
* fix: donation links

---------

Co-authored-by: dni  <office@dnilabs.com>
2024-05-16 10:05:22 +02:00
dni ⚡andGitHub 63ce506d29 fix: add cln unspecified error code bolt11 error to errorcodes (#2503)
{'code': -32602, 'message': 'Invalid bolt11: Prefix bc is not for regtest'}```
2024-05-16 09:59:54 +02:00
Vlad StanandGitHub 5114bd4a47 fix: link to demo server 2024-05-15 11:57:24 +03:00
dni ⚡andGitHub 05a244d8fd fix: refresh payments on payment success (#2502)
* fix: refresh payments on payment
2024-05-14 19:22:14 +03:00
dni ⚡andGitHub 019995078c fix: init wallet balance (#2501) 2024-05-14 18:56:57 +03:00
Vlad StanandGitHub f37cb6481c fix: copy invoice (#2500)
* fix: copy invoice
* chore: add mixins
* chore: make bundle
2024-05-14 17:55:45 +02:00
dni ⚡andGitHub 365f9a3923 fix: mobileSimple in paymentlist (#2498) 2024-05-14 13:57:04 +02:00
dni ⚡andGitHub bb4dd4fe35 fix: payment list currency (#2496)
* fix: payment list currency
2024-05-14 13:49:00 +02:00
Vlad StanandGitHub d1ae531750 fix: add methods back (#2495) 2024-05-14 13:48:33 +02:00
8ee2948f71 fix: payment list updates (#2493)
* fix: payment list updates

---------

Co-authored-by: Vlad Stan <stan.v.vlad@gmail.com>
2024-05-14 13:06:44 +02:00
ArcandGitHub ab3fe79a7e typo: fix opensats badge (#2494) 2024-05-14 12:35:39 +02:00
dni ⚡andGitHub 32596758cc fix: show proper total balances fix cleanups (#2490)
payments are not deleted oif we delete a wallets, so to get a accurate
total representation of the lnbits balance we need to create the
balances view based on the wallets table, not payments, else deleted
balances will still show up.

2nd, delete_unused_wallets and delete_accounts was never working if
because they never got an updated_at time, so i just check if its null
else i check to timedelta on created_at
2024-05-13 18:01:53 +01:00
dni ⚡andGitHub a5623ef7c3 feat: add payments table to user manager (#2491)
* feat: add payments table to user manager

refactor payments table and payment chart into components and add them
to usermanager

* bundle
2024-05-13 18:01:01 +01:00
9933484558 refactor: get_balance_delta and use pydantic model for openapi docs (#2492)
* refactor: `get_balance_delta` and use pydantic model for openapi docs

---------

Co-authored-by: Vlad Stan <stan.v.vlad@gmail.com>
2024-05-13 17:59:29 +02:00
dni ⚡andGitHub 78fc28558c refactor: catch payment and invoice error at faspi exceptionhandler level (#2484)
refactor exceptionhandlers into `exception.py` also now always throw
payment error when pay_invoice and invoice errors when create_invoice.

return a status flag with the detailed error message. with a 520
response
2024-05-13 17:58:48 +02:00
dni ⚡andGitHub 1e752dc3d2 test: services create and pay invoice (#2452)
* test: services create and pay invoice
* add more tests
* check with fundingsource
* check status
2024-05-13 16:55:38 +02:00
dni ⚡andGitHub 6730c6ed67 refactor: fix duplicate keychecker (#2339)
* refactor: fix duplicate keychecker

- refactor KeyChecker to be more approachable
- only 1 sql query needed even if you use `get_key_type`
- rename `WalletType` to `KeyType` wallet type was misleading

fix test

sorting

* fixup!

* revert 404
2024-05-13 15:26:25 +01:00
Vlad StanandGitHub 9f8942a921 chore: sort funding sources (#2489) 2024-05-10 17:45:51 +02:00
dni ⚡andGitHub 33c68065d5 fix: usermanager visible for everyone (#2488)
* fix: usermanager sidemenu
was missed by merge
2024-05-10 13:24:51 +02:00
9ca14f200d feat: usermanager (#2139)
* feat: usermanager

---------

Co-authored-by: Vlad Stan <stan.v.vlad@gmail.com>
2024-05-10 12:06:46 +02:00
eae5002b69 fix: pay invoice status (#2481)
* fix: rest `pay_invoice` pending instead of failed
* fix: rpc `pay_invoice` pending instead of failed
* fix: return "failed" value for payment
* fix: handle failed status for LNbits funding source
* chore: `phoenixd` todo
* test: fix condition
* fix: wait for payment status to be updated
* fix: fail payment when explicit status provided

---------

Co-authored-by: dni  <office@dnilabs.com>
2024-05-10 11:49:50 +02:00
dni ⚡andGitHub b9e62bfceb refactor: move logger function from app.py to utils/logger.py (#2454)
* refactor: move logger function from `app.py` to `utils/logger.py`

just some simply refactoring to clean up app.py

* while true
2024-05-09 17:51:18 +01:00
dni ⚡andGitHub f60122c64a feat: update docker image to debian 12 (bookwork) (#2486)
postgres client install was failing for bullseye, i think its time
2024-05-09 18:26:45 +02:00
dni ⚡andGitHub c030ccc4f8 fix: no need to create fake admin (#2485)
already is done inside regtest
2024-05-09 16:56:11 +02:00
0076a85fdb fix: typo in phoenixd wallet (#2473)
Co-authored-by: Vlad Stan <stan.v.vlad@gmail.com>
Co-authored-by: Pavol Rusnak <pavol@rusnak.io>
2024-05-03 18:49:09 +02:00
c3d37a460c Improved customisable homepage and added badge (#2474)
* Improved customisable homepage and added badge

* Added filled to styling of drop down

* format

* Wrong model

* lint hack

* Update .env.example

Co-authored-by: Vlad Stan <stan.v.vlad@gmail.com>

* reverted

* Spelling

* More explicit

* format

* Added if for badge

* spellling

* Fix for None

---------

Co-authored-by: Vlad Stan <stan.v.vlad@gmail.com>
2024-04-30 08:08:57 +01:00
c04c13b2f8 feat: phoenixd wallet integration (#2362)
* phoenixd integration
---------

Co-authored-by: Vlad Stan <stan.v.vlad@gmail.com>
2024-04-26 10:18:38 +02:00
dni ⚡andGitHub 4b4bed59cd feat: corelightning maxfee and custom pay command (#2464)
* feat: corelightning `maxfee` and custom pay command
we should use maxfee instead of calculating the ratio and pass it
through.
also make it possible to run a custom pay command
* change for cln rest aswell
2024-04-25 12:54:00 +02:00
dni ⚡andGitHub 4a0fb59461 chore: use prettier for all of the codebase (#2466)
* chore: use prettier for all of the codebase
we only checked `lnbits` dir before
2024-04-25 11:13:08 +02:00
Pavol RusnakandGitHub f5293ca645 fix: compatibility with Python 3.12 (#2463)
by updating grpc a uvloop dependencies to latest
2024-04-24 08:39:41 +02:00
Vlad StanandGitHub b2ff2d8cee [test] add tests for lnbits funding source (#2460) 2024-04-24 09:31:23 +03:00
Vlad StanandGitHub 8d3b156738 [test] add tests for eclair funding source (#2459)
* fix: test data

* test: add `status` tests

* refactor: try-catch

* test: create invoice tests

* test: add first `payinvoice` test

* test: add pay_invoice error test

* feat: allow more test options

* test: add pending tests

* fix: make check

* test: add, pending no fee

* fix: make consistent with other API calls

* test: more assertions

* test: add pending

* test: first payment status test

* test: pending status

* refactor: remove duplicate code

* refactor: rename field

* chore: code format

* chore: uniform
2024-04-23 16:18:52 +01:00
dni ⚡andPavol Rusnak 00f39a2007 test: add unit for fee_reserve and service_fee
:)

sorting
2024-04-22 11:38:24 +02:00
Vlad StanandGitHub 4ac30116a9 feat: add settings.lnbits_running (#2450)
* feat: add `settings.lnbits_runing `
2024-04-22 12:33:53 +03:00
dni ⚡andGitHub e91096c535 feat: remove magic argument parser from lnbits command (#2448)
got the idea from: https://github.com/lnbits/lnbits/issues/2447
arguments it should be explicity allowed with `click` and a description
should be added like here.
2024-04-19 13:23:56 +02:00
dni ⚡andGitHub e607ab7a3e test: restructure tests (#2444)
unit, api, wallets
* only run test-api for migration
2024-04-19 13:22:06 +02:00
Vlad StanandGitHub 67fdb77339 test: unit tests for lndrpc (#2442) 2024-04-19 13:21:21 +02:00
Pavol Rusnak 4f118c5f98 chore: make bundle 2024-04-18 15:44:17 +02:00
Pavol Rusnak 33ace85f7d i18n: refresh translations using AI script 2024-04-18 15:44:17 +02:00
Pavol Rusnak 33c50100ab fix: small update to i18n-ai-tool system prompt 2024-04-18 15:44:17 +02:00
782cbfc77f fix: balances view on use non deleted wallets (#2385)
* fix: balances view on use non deleted wallets

closes #2224

* fixup! fix: balances view on use non deleted wallets

---------

Co-authored-by: Pavol Rusnak <pavol@rusnak.io>
2024-04-18 11:49:40 +01:00
dni ⚡andGitHub bbfc301440 fix: broken lnurl_callback (#2445)
* fix: broken lnurl_callback
2024-04-18 12:16:00 +02:00
dni ⚡andGitHub 98ec59df96 feat: adhere to ruff's B rules (#2423)
* feat: adhere to ruff's `B` rules
last of the ruff checks.
closes #2308
* B904
* B008
* B005
* B025
* cleanup on fake
2024-04-17 13:11:51 +02:00
dni ⚡andGitHub e13a37c193 FEAT: add PYPI python package release workflow on tag (#1628)
* add pypi worflow, pyproject types, package metadata, ignore python package build, docker build fails if poetry uses readme for python package

* add pypi to release
2024-04-17 10:53:57 +02:00
dni ⚡andGitHub 0c3aabf77a feat: catch_everything_and_restart print name of the task (#2417)
remove type from `Coroutine` from the create_tasks
2024-04-17 10:51:07 +02:00
d9880c4de8 Clarified top-up success msg (#2381)
* Update admin_api.py
Common misconception is that the top up related to the funds on the funding source. 
Success msg  extended with info that correlated funds on funding source are needed and the amount is virtual until fitting.

* chore: code format
* feat: customise top-up message
* refactor: move the `Quasar.Notify` to `components.js`
* refactor: use `this.$q.notify` instead of `Quasar.Notify.create`

---------

Co-authored-by: Vlad Stan <stan.v.vlad@gmail.com>
2024-04-17 09:55:57 +02:00
ArcandGitHub 0a4eb78ef0 Fixes ad issue on homepage + readme badges (#2422)
Fixes broken ad layout on homepage
* Removed telegram link
2024-04-17 08:54:48 +02:00
dni ⚡andGitHub daa1b5a313 chore: adhere to ruff's RUF rules, 2nd try (#2420)
* chore: adhere to ruff's `RUF` rules, 2nd try
closes #2382
2024-04-17 07:36:22 +02:00
ArcandGitHub d78f6a1f9e Added extra default ads to support project (#2421) 2024-04-16 16:26:04 +02:00
dni ⚡andGitHub 839fe8b96d feat: add PEP561 marker for types (#2415)
tasks.py:8: error: Skipping analyzing "lnbits.tasks": module is
installed, but missing library stubs or py.typed marker
[import-untyped]

https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
2024-04-16 16:16:45 +02:00
25661ddff5 chore: remove lnurl wallet and withdraw feature (#2293)
* chore: remove lnurl wallet and withdraw feature
this feature is undocumented and the code is very outdated. i don't think it is worth to keep.
looking at the `/lnurlwallet` endpoint for example, it creates a new user and wallet without even checking if the creation of users is allowed
* remove lnurl callback

---------

Co-authored-by: Arc <33088785+arcbtc@users.noreply.github.com>
2024-04-16 14:10:32 +02:00
dni ⚡andGitHub 55eb3be5d5 feat: make workflow reuseable for external repo (#2419)
* feat: make workflow reuseable for external repo

* fixup!
2024-04-16 10:43:53 +01:00
dni ⚡andGitHub 0714570242 fix: ruff linting broke (#2418)
fix linting
2024-04-16 08:34:33 +02:00
69ce0e565b [test] create unit-test framework for RPC wallets (#2396)
---------

Co-authored-by: dni  <office@dnilabs.com>
2024-04-15 17:24:28 +02:00
dni ⚡andPavol Rusnak b145bff566 chore: adhere to ruff's UP
basically use `list` and `type` instead of `List` and `Type`

this is save to use for python3.9 and has been deprecated. also has some
performance drawbacks.
read more here: https://docs.astral.sh/ruff/rules/non-pep585-annotation/
2024-04-15 13:38:04 +02:00
dni ⚡andGitHub a158056b99 chore: enable migration tests again (#2414)
PR has been merged. https://github.com/lnbits/lnbits-extensions/pull/300
2024-04-15 11:12:03 +02:00
Vlad StanandGitHub e8479941c8 fix: check installed extensions, not available ones (#2413) 2024-04-15 10:21:15 +03:00
6d5ad9e229 chore: adhere to ruff's "N" rules (#2377)
* chore: adhere to ruff's "N" rules

WARN: reinstall failing extensions!

bunch of more consistent variable naming. inspired by this issue.
https://github.com/lnbits/lnbits/issues/2308

* fixup! chore: adhere to ruff's "N" rules
* rename to funding_source
* skip jmeter

---------

Co-authored-by: Pavol Rusnak <pavol@rusnak.io>
2024-04-15 09:02:21 +02:00
dni ⚡andGitHub 055426ab53 chore: prepare version update to 0.12.6 (#2407)
needed in preparation of https://github.com/lnbits/lnbits/pull/2377
2024-04-12 17:29:08 +02:00
dni ⚡andGitHub 4bafe97167 fix: fastapi status import (#2408)
should use `from http import HTTPStatus`
2024-04-12 15:56:54 +02:00
dni ⚡andGitHub 8aef6cd416 chore: update prettier (#2405)
update to new prettier version with some new formatting
2024-04-12 09:00:31 +02:00
adb8f9bdec feat: add funding_source_max_retries env setting (#2404)
* feat: add `funding_source_max_retries` env setting

* feat: default to zero retries

* feat: exponential retry time increase

* chore: Let's use the same value as the default

Co-authored-by: Pavol Rusnak <pavol@rusnak.io>

* feat: using 0.25 leads to less awkward numbers

Co-authored-by: Pavol Rusnak <pavol@rusnak.io>

---------

Co-authored-by: Pavol Rusnak <pavol@rusnak.io>
2024-04-11 17:29:25 +01:00
162 changed files with 10653 additions and 4721 deletions
+1
View File
@@ -9,6 +9,7 @@ lnbits/static/bundle.js
lnbits/static/bundle.css lnbits/static/bundle.css
*.md *.md
!README.md
*.log *.log
.env .env
+13 -3
View File
@@ -15,7 +15,7 @@ LNBITS_ADMIN_UI=false
# Change theme # Change theme
LNBITS_SITE_TITLE="LNbits" LNBITS_SITE_TITLE="LNbits"
LNBITS_SITE_TAGLINE="free and open-source lightning wallet" LNBITS_SITE_TAGLINE="free and open-source lightning wallet"
LNBITS_SITE_DESCRIPTION="Some description about your service, will display if title is not 'LNbits'" LNBITS_SITE_DESCRIPTION="The world's most powerful suite of bitcoin tools. Run for yourself, for others, or as part of a stack."
# Choose from bitcoin, mint, flamingo, freedom, salvador, autumn, monochrome, classic, cyber # Choose from bitcoin, mint, flamingo, freedom, salvador, autumn, monochrome, classic, cyber
LNBITS_THEME_OPTIONS="classic, bitcoin, flamingo, freedom, mint, autumn, monochrome, salvador, cyber" LNBITS_THEME_OPTIONS="classic, bitcoin, flamingo, freedom, mint, autumn, monochrome, salvador, cyber"
# LNBITS_CUSTOM_LOGO="https://lnbits.com/assets/images/logo/logo.svg" # LNBITS_CUSTOM_LOGO="https://lnbits.com/assets/images/logo/logo.svg"
@@ -28,12 +28,15 @@ PORT=5000
###################################### ######################################
# which fundingsources are allowed in the admin ui # which fundingsources are allowed in the admin ui
LNBITS_ALLOWED_FUNDING_SOURCES="VoidWallet, FakeWallet, CoreLightningWallet, CoreLightningRestWallet, LndRestWallet, EclairWallet, LndWallet, LnTipsWallet, LNPayWallet, LNbitsWallet, AlbyWallet, ZBDWallet, OpenNodeWallet" LNBITS_ALLOWED_FUNDING_SOURCES="VoidWallet, FakeWallet, CoreLightningWallet, CoreLightningRestWallet, LndRestWallet, EclairWallet, LndWallet, LnTipsWallet, LNPayWallet, LNbitsWallet, AlbyWallet, ZBDWallet, PhoenixdWallet, OpenNodeWallet"
LNBITS_BACKEND_WALLET_CLASS=VoidWallet LNBITS_BACKEND_WALLET_CLASS=VoidWallet
# VoidWallet is just a fallback that works without any actual Lightning capabilities, # VoidWallet is just a fallback that works without any actual Lightning capabilities,
# just so you can see the UI before dealing with this file. # just so you can see the UI before dealing with this file.
# How many times to retry connectiong to the Funding Source before defaulting to the VoidWallet
# FUNDING_SOURCE_MAX_RETRIES=4
# Invoice expiry for LND, CLN, Eclair, LNbits funding sources # Invoice expiry for LND, CLN, Eclair, LNbits funding sources
LIGHTNING_INVOICE_EXPIRY=3600 LIGHTNING_INVOICE_EXPIRY=3600
@@ -55,7 +58,7 @@ CORELIGHTNING_REST_MACAROON="/path/to/clnrest/access.macaroon" # or BASE64/HEXS
CORELIGHTNING_REST_CERT="/path/to/clnrest/tls.cert" CORELIGHTNING_REST_CERT="/path/to/clnrest/tls.cert"
# LnbitsWallet # LnbitsWallet
LNBITS_ENDPOINT=https://legend.lnbits.com LNBITS_ENDPOINT=https://demo.lnbits.com
LNBITS_KEY=LNBITS_ADMIN_KEY LNBITS_KEY=LNBITS_ADMIN_KEY
# LndWallet # LndWallet
@@ -88,6 +91,10 @@ ALBY_ACCESS_TOKEN=ALBY_ACCESS_TOKEN
ZBD_API_ENDPOINT=https://api.zebedee.io/v0/ ZBD_API_ENDPOINT=https://api.zebedee.io/v0/
ZBD_API_KEY=ZBD_ACCESS_TOKEN ZBD_API_KEY=ZBD_ACCESS_TOKEN
# PhoenixdWallet
PHOENIXD_API_ENDPOINT=http://localhost:9740/
PHOENIXD_API_PASSWORD=PHOENIXD_KEY
# OpenNodeWallet # OpenNodeWallet
OPENNODE_API_ENDPOINT=https://api.opennode.com/ OPENNODE_API_ENDPOINT=https://api.opennode.com/
OPENNODE_KEY=OPENNODE_ADMIN_KEY OPENNODE_KEY=OPENNODE_ADMIN_KEY
@@ -175,6 +182,9 @@ LNBITS_DEFAULT_WALLET_NAME="LNbits wallet"
# LNBITS_AD_SPACE_TITLE="Supported by" # LNBITS_AD_SPACE_TITLE="Supported by"
# csv ad space, format "<url>;<img-light>;<img-dark>, <url>;<img-light>;<img-dark>", extensions can choose to honor # csv ad space, format "<url>;<img-light>;<img-dark>, <url>;<img-light>;<img-dark>", extensions can choose to honor
# LNBITS_AD_SPACE="https://shop.lnbits.com/;https://raw.githubusercontent.com/lnbits/lnbits/main/lnbits/static/images/lnbits-shop-light.png;https://raw.githubusercontent.com/lnbits/lnbits/main/lnbits/static/images/lnbits-shop-dark.png" # LNBITS_AD_SPACE="https://shop.lnbits.com/;https://raw.githubusercontent.com/lnbits/lnbits/main/lnbits/static/images/lnbits-shop-light.png;https://raw.githubusercontent.com/lnbits/lnbits/main/lnbits/static/images/lnbits-shop-dark.png"
# LNBITS_SHOW_HOME_PAGE_ELEMENTS=true # if set to true, the ad space will be displayed on the home page
# LNBITS_CUSTOM_BADGE="USE WITH CAUTION - LNbits wallet is still in BETA"
# LNBITS_CUSTOM_BADGE_COLOR="warning"
# Hides wallet api, extensions can choose to honor # Hides wallet api, extensions can choose to honor
LNBITS_HIDE_API=false LNBITS_HIDE_API=false
+1 -1
View File
@@ -1 +1 @@
custom: https://legend.lnbits.com/paywall/GAqKguK5S8f6w5VNjS9DfK custom: https://demo.lnbits.com/lnurlp/link/fH59GD
+31 -1
View File
@@ -12,7 +12,7 @@ jobs:
lint: lint:
uses: ./.github/workflows/lint.yml uses: ./.github/workflows/lint.yml
tests: test-api:
needs: [ lint ] needs: [ lint ]
strategy: strategy:
matrix: matrix:
@@ -20,6 +20,35 @@ jobs:
db-url: ["", "postgres://lnbits:lnbits@0.0.0.0:5432/lnbits"] db-url: ["", "postgres://lnbits:lnbits@0.0.0.0:5432/lnbits"]
uses: ./.github/workflows/tests.yml uses: ./.github/workflows/tests.yml
with: with:
custom-pytest: "poetry run pytest tests/api"
python-version: ${{ matrix.python-version }}
db-url: ${{ matrix.db-url }}
secrets:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
test-wallets:
needs: [ lint ]
strategy:
matrix:
python-version: ["3.9", "3.10"]
db-url: ["", "postgres://lnbits:lnbits@0.0.0.0:5432/lnbits"]
uses: ./.github/workflows/tests.yml
with:
custom-pytest: "poetry run pytest tests/wallets"
python-version: ${{ matrix.python-version }}
db-url: ${{ matrix.db-url }}
secrets:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
test-unit:
needs: [ lint ]
strategy:
matrix:
python-version: ["3.9", "3.10"]
db-url: ["", "postgres://lnbits:lnbits@0.0.0.0:5432/lnbits"]
uses: ./.github/workflows/tests.yml
with:
custom-pytest: "poetry run pytest tests/unit"
python-version: ${{ matrix.python-version }} python-version: ${{ matrix.python-version }}
db-url: ${{ matrix.db-url }} db-url: ${{ matrix.db-url }}
secrets: secrets:
@@ -48,6 +77,7 @@ jobs:
python-version: ["3.9"] python-version: ["3.9"]
backend-wallet-class: ["LndRestWallet", "LndWallet", "CoreLightningWallet", "CoreLightningRestWallet", "LNbitsWallet", "EclairWallet"] backend-wallet-class: ["LndRestWallet", "LndWallet", "CoreLightningWallet", "CoreLightningRestWallet", "LNbitsWallet", "EclairWallet"]
with: with:
custom-pytest: "poetry run pytest tests/regtest"
python-version: ${{ matrix.python-version }} python-version: ${{ matrix.python-version }}
backend-wallet-class: ${{ matrix.backend-wallet-class }} backend-wallet-class: ${{ matrix.backend-wallet-class }}
secrets: secrets:
+1 -1
View File
@@ -26,7 +26,7 @@ jobs:
runs-on: ${{ matrix.os-version }} runs-on: ${{ matrix.os-version }}
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: ./.github/actions/prepare - uses: lnbits/lnbits/.github/actions/prepare@dev
with: with:
python-version: ${{ inputs.python-version }} python-version: ${{ inputs.python-version }}
node-version: ${{ matrix.node-version }} node-version: ${{ matrix.node-version }}
+14 -22
View File
@@ -3,8 +3,9 @@ name: regtest
on: on:
workflow_call: workflow_call:
inputs: inputs:
make: custom-pytest:
default: test description: "Custom pytest arguments"
required: true
type: string type: string
python-version: python-version:
default: "3.9" default: "3.9"
@@ -26,19 +27,10 @@ jobs:
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Set up Docker Buildx - name: docker build
if: ${{ inputs.backend-wallet-class == 'LNbitsWallet' }} if: ${{ inputs.backend-wallet-class == 'LNbitsWallet' }}
uses: docker/setup-buildx-action@v3 run: |
docker build -t lnbits/lnbits .
- name: Build and push
if: ${{ inputs.backend-wallet-class == 'LNbitsWallet' }}
uses: docker/build-push-action@v5
with:
context: .
push: false
tags: lnbits/lnbits:latest
cache-from: type=registry,ref=lnbits/lnbits:latest
cache-to: type=inline
- name: Setup Regtest - name: Setup Regtest
run: | run: |
@@ -52,10 +44,6 @@ jobs:
with: with:
python-version: ${{ inputs.python-version }} python-version: ${{ inputs.python-version }}
- name: Create fake admin
if: ${{ inputs.backend-wallet-class == 'LNbitsWallet' }}
run: docker exec lnbits-lnbits-1 poetry run python tools/create_fake_admin.py
- name: Run pytest - name: Run pytest
uses: pavelzw/pytest-action@v2 uses: pavelzw/pytest-action@v2
env: env:
@@ -76,15 +64,14 @@ jobs:
LNBITS_KEY: "d08a3313322a4514af75d488bcc27eee" LNBITS_KEY: "d08a3313322a4514af75d488bcc27eee"
ECLAIR_URL: http://127.0.0.1:8082 ECLAIR_URL: http://127.0.0.1:8082
ECLAIR_PASS: lnbits ECLAIR_PASS: lnbits
LNBITS_DATA_FOLDER: "./tests/data"
PYTHONUNBUFFERED: 1 PYTHONUNBUFFERED: 1
DEBUG: true DEBUG: true
with: with:
verbose: false verbose: true
job-summary: true job-summary: true
emoji: false emoji: false
click-to-expand: false click-to-expand: true
custom-pytest: poetry run pytest custom-pytest: ${{ inputs.custom-pytest }}
report-title: "regtest (${{ inputs.python-version }}, ${{ inputs.backend-wallet-class }}" report-title: "regtest (${{ inputs.python-version }}, ${{ inputs.backend-wallet-class }}"
- name: Upload coverage to Codecov - name: Upload coverage to Codecov
@@ -93,3 +80,8 @@ jobs:
file: ./coverage.xml file: ./coverage.xml
token: ${{ secrets.CODECOV_TOKEN }} token: ${{ secrets.CODECOV_TOKEN }}
verbose: true verbose: true
- name: docker lnbits logs
if: ${{ inputs.backend-wallet-class == 'LNbitsWallet' }}
run: |
docker logs lnbits-lnbits-1
+10
View File
@@ -10,6 +10,7 @@ permissions:
contents: write contents: write
jobs: jobs:
release: release:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
@@ -29,3 +30,12 @@ jobs:
secrets: secrets:
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
pypi:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build and publish to pypi
uses: JRubics/poetry-publish@v1.15
with:
pypi_token: ${{ secrets.PYPI_API_KEY }}
+7 -5
View File
@@ -3,6 +3,10 @@ name: tests
on: on:
workflow_call: workflow_call:
inputs: inputs:
custom-pytest:
description: "Custom pytest arguments"
required: true
type: string
python-version: python-version:
default: "3.9" default: "3.9"
type: string type: string
@@ -50,16 +54,14 @@ jobs:
env: env:
LNBITS_DATABASE_URL: ${{ inputs.db-url }} LNBITS_DATABASE_URL: ${{ inputs.db-url }}
LNBITS_BACKEND_WALLET_CLASS: FakeWallet LNBITS_BACKEND_WALLET_CLASS: FakeWallet
FAKE_WALLET_SECRET: "ToTheMoon1"
LNBITS_DATA_FOLDER: "./tests/data"
PYTHONUNBUFFERED: 1 PYTHONUNBUFFERED: 1
DEBUG: true DEBUG: true
with: with:
verbose: false verbose: true
job-summary: true job-summary: true
emoji: false emoji: false
click-to-expand: false click-to-expand: true
custom-pytest: poetry run pytest custom-pytest: ${{ inputs.custom-pytest }}
report-title: "test (${{ inputs.python-version }}, ${{ inputs.db-url }})" report-title: "test (${{ inputs.python-version }}, ${{ inputs.db-url }})"
- name: Upload coverage to Codecov - name: Upload coverage to Codecov
+3
View File
@@ -51,3 +51,6 @@ lnbits-backup.zip
# Ignore extensions (post installable extension PR) # Ignore extensions (post installable extension PR)
extensions extensions
upgrades/ upgrades/
# builded python package
dist
+1 -1
View File
@@ -23,7 +23,7 @@ repos:
- id: ruff - id: ruff
args: [ --fix, --exit-non-zero-on-fix ] args: [ --fix, --exit-non-zero-on-fix ]
- repo: https://github.com/pre-commit/mirrors-prettier - repo: https://github.com/pre-commit/mirrors-prettier
rev: '50c5478ed9e10bf360335449280cf2a67f4edb7a' rev: "v4.0.0-alpha.8"
hooks: hooks:
- id: prettier - id: prettier
types_or: [css, javascript, html, json] types_or: [css, javascript, html, json]
+4
View File
@@ -11,3 +11,7 @@
**/lnbits/static/vendor **/lnbits/static/vendor
**/lnbits/static/bundle.* **/lnbits/static/bundle.*
**/lnbits/static/css/* **/lnbits/static/css/*
flake.lock
.venv
+5 -4
View File
@@ -1,4 +1,4 @@
FROM python:3.10-slim-bullseye FROM python:3.10-slim-bookworm
RUN apt-get clean RUN apt-get clean
RUN apt-get update RUN apt-get update
@@ -8,9 +8,10 @@ RUN curl -sSL https://install.python-poetry.org | python3 -
ENV PATH="/root/.local/bin:$PATH" ENV PATH="/root/.local/bin:$PATH"
# needed for backups postgresql-client version 14 (pg_dump) # needed for backups postgresql-client version 14 (pg_dump)
RUN apt-get install -y apt-utils wget RUN apt install -y postgresql-common ca-certificates
RUN echo "deb http://apt.postgresql.org/pub/repos/apt bullseye-pgdg main" > /etc/apt/sources.list.d/pgdg.list RUN install -d /usr/share/postgresql-common/pgdg
RUN wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add - RUN curl -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc --fail https://www.postgresql.org/media/keys/ACCC4CF8.asc
RUN sh -c 'echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt bookworm-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
RUN apt-get update RUN apt-get update
RUN apt-get install -y postgresql-client-14 RUN apt-get install -y postgresql-client-14
+21 -10
View File
@@ -6,8 +6,10 @@ format: prettier black ruff
check: mypy pyright checkblack checkruff checkprettier checkbundle check: mypy pyright checkblack checkruff checkprettier checkbundle
test: test-unit test-wallets test-api test-regtest
prettier: prettier:
poetry run ./node_modules/.bin/prettier --write lnbits poetry run ./node_modules/.bin/prettier --write .
pyright: pyright:
poetry run ./node_modules/.bin/pyright poetry run ./node_modules/.bin/pyright
@@ -25,7 +27,7 @@ checkruff:
poetry run ruff check . poetry run ruff check .
checkprettier: checkprettier:
poetry run ./node_modules/.bin/prettier --check lnbits poetry run ./node_modules/.bin/prettier --check .
checkblack: checkblack:
poetry run black --check . poetry run black --check .
@@ -36,23 +38,32 @@ checkeditorconfig:
dev: dev:
poetry run lnbits --reload poetry run lnbits --reload
test: test-wallets:
LNBITS_BACKEND_WALLET_CLASS="FakeWallet" \ LNBITS_BACKEND_WALLET_CLASS="FakeWallet" \
FAKE_WALLET_SECRET="ToTheMoon1" \
LNBITS_DATA_FOLDER="./tests/data" \
PYTHONUNBUFFERED=1 \ PYTHONUNBUFFERED=1 \
DEBUG=true \ DEBUG=true \
poetry run pytest poetry run pytest tests/wallets
test-real-wallet: test-unit:
LNBITS_DATA_FOLDER="./tests/data" \ LNBITS_BACKEND_WALLET_CLASS="FakeWallet" \
PYTHONUNBUFFERED=1 \ PYTHONUNBUFFERED=1 \
DEBUG=true \ DEBUG=true \
poetry run pytest poetry run pytest tests/unit
test-api:
LNBITS_BACKEND_WALLET_CLASS="FakeWallet" \
PYTHONUNBUFFERED=1 \
DEBUG=true \
poetry run pytest tests/api
test-regtest:
PYTHONUNBUFFERED=1 \
DEBUG=true \
poetry run pytest tests/regtest
test-migration: test-migration:
LNBITS_ADMIN_UI=True \ LNBITS_ADMIN_UI=True \
make test make test-api
HOST=0.0.0.0 \ HOST=0.0.0.0 \
PORT=5002 \ PORT=5002 \
LNBITS_DATA_FOLDER="./tests/data" \ LNBITS_DATA_FOLDER="./tests/data" \
+6 -12
View File
@@ -1,22 +1,16 @@
<picture > <picture >
<source media="(prefers-color-scheme: dark)" srcset="https://i.imgur.com/QE6SIrs.png" style="width:300px"> <source media="(prefers-color-scheme: dark)" srcset="https://i.imgur.com/QE6SIrs.png" style="width:300px">
<img src="https://i.imgur.com/fyKPgVT.png" style="width:300px"> <img src="https://i.imgur.com/fyKPgVT.png" style="width:300px">
</picture> </picture>
<b>(BETA)</b> ![phase: beta](https://img.shields.io/badge/phase-beta-C41E3A) [![license-badge]](LICENSE) [![docs-badge]][docs] ![PRs: welcome](https://img.shields.io/badge/PRs-Welcome-08A04B) [<img src="https://img.shields.io/badge/community_chat-Telegram-24A1DE">](https://t.me/lnbits) [<img src="https://img.shields.io/badge/supported_by-%3E__OpenSats-f97316">](https://opensats.org)
[![license-badge]](LICENSE) [![docs-badge]][docs]
![Lightning network wallet](https://i.imgur.com/DeIiO0y.png) ![Lightning network wallet](https://i.imgur.com/DeIiO0y.png)
# The world's most powerful suite of bitcoin tools. # The world's most powerful suite of bitcoin tools.
## Run for yourself, for others, or as part of a stack. ## Run for yourself, for others, or as part of a stack.
(Join us on [https://t.me/lnbits](https://t.me/lnbits)) LNbits is beta, for responsible disclosure of any concerns please contact an admin in the community chat.
LNbits is beta, for responsible disclosure of any concerns please contact an admin in [https://t.me/lnbits](https://t.me/lnbits)
LNbits is a Python server that sits on top of any funding source. It can be used as: LNbits is a Python server that sits on top of any funding source. It can be used as:
@@ -36,7 +30,7 @@ LNbits is inspired by all the great work of [opennode.com](https://www.opennode.
## Running LNbits ## Running LNbits
Test on our demo server [legend.lnbits.com](https://legend.lnbits.com), or on [lnbits.com](https://lnbits.com) software as a service, where you can spin up an LNbits instance for 21sats per hr. Test on our demo server [demo.lnbits.com](https://demo.lnbits.com), or on [lnbits.com](https://lnbits.com) software as a service, where you can spin up an LNbits instance for 21sats per hr.
See the [install guide](https://github.com/lnbits/lnbits/blob/main/docs/guide/installation.md) for details on installation and setup. See the [install guide](https://github.com/lnbits/lnbits/blob/main/docs/guide/installation.md) for details on installation and setup.
@@ -50,7 +44,7 @@ LNbits is packaged with tools to help manage funds, such as a table of transacti
Extend YOUR LNbits to meet YOUR needs. Extend YOUR LNbits to meet YOUR needs.
All non-core features are installed as extensions, reducing your code base and making your LNbits unique to you. Extend your LNbits install in any direction, and even create and share your own extensions. All non-core features are installed as extensions, reducing your code base and making your LNbits unique to you. Extend your LNbits install in any direction, and even create and share your own extensions.
<img src="https://i.imgur.com/aEBpwJF.png" style="width:800px"> <img src="https://i.imgur.com/aEBpwJF.png" style="width:800px">
@@ -74,7 +68,7 @@ As well as working great in a browser, LNbits has native IoS and Android apps as
## Tip us ## Tip us
If you like this project [send some tip love](https://legend.lnbits.com/paywall/GAqKguK5S8f6w5VNjS9DfK)! If you like this project [send some tip love](https://demo.lnbits.com/lnurlp/link/fH59GD)!
[docs]: https://github.com/lnbits/lnbits/wiki [docs]: https://github.com/lnbits/lnbits/wiki
[docs-badge]: https://img.shields.io/badge/docs-lnbits.org-673ab7.svg [docs-badge]: https://img.shields.io/badge/docs-lnbits.org-673ab7.svg
+2 -4
View File
@@ -5,8 +5,6 @@ title: API reference
nav_order: 3 nav_order: 3
--- ---
# API reference
API reference [Swagger Docs](https://demo.lnbits.com/docs)
=============
[Swagger Docs](https://legend.lnbits.com/docs)
+11 -10
View File
@@ -5,30 +5,27 @@ nav_order: 4
has_children: true has_children: true
--- ---
# For developers
For developers
==============
Thanks for contributing :) Thanks for contributing :)
# Run
Run
=====
This starts the lnbits uvicorn server This starts the lnbits uvicorn server
```bash ```bash
poetry run lnbits poetry run lnbits
``` ```
This starts the lnbits uvicorn with hot reloading. This starts the lnbits uvicorn with hot reloading.
```bash ```bash
make dev make dev
# or # or
poetry run lnbits --reload poetry run lnbits --reload
``` ```
Precommit hooks # Precommit hooks
=====
This ensures that all commits adhere to the formatting and linting rules. This ensures that all commits adhere to the formatting and linting rules.
@@ -36,31 +33,35 @@ This ensures that all commits adhere to the formatting and linting rules.
make install-pre-commit-hook make install-pre-commit-hook
``` ```
Tests # Tests
=====
This project has unit tests that help prevent regressions. Before you can run the tests, you must install a few dependencies: This project has unit tests that help prevent regressions. Before you can run the tests, you must install a few dependencies:
```bash ```bash
poetry install poetry install
npm i npm i
``` ```
Then to run the tests: Then to run the tests:
```bash ```bash
make test make test
``` ```
Run formatting: Run formatting:
```bash ```bash
make format make format
``` ```
Run mypy checks: Run mypy checks:
```bash ```bash
poetry run mypy poetry run mypy
``` ```
Run everything: Run everything:
```bash ```bash
make all make all
``` ```
+19 -14
View File
@@ -5,11 +5,10 @@ title: Making extensions
nav_order: 2 nav_order: 2
--- ---
# Extension set up
Extension set up
=================
Start off by creating a fork of the [example extension](https://github.com/lnbits/example) into own GitHub repository and rename the repository to `mysuperplugin`: Start off by creating a fork of the [example extension](https://github.com/lnbits/example) into own GitHub repository and rename the repository to `mysuperplugin`:
```sh ```sh
cd [my-working-folder] cd [my-working-folder]
git clone https://github.com/[my-user-name]/mysuperplugin.git --depth=1 # Let's not use dashes or anything; it doesn't like those. git clone https://github.com/[my-user-name]/mysuperplugin.git --depth=1 # Let's not use dashes or anything; it doesn't like those.
@@ -18,6 +17,7 @@ rm -rf .git/
find . -type f -print0 | xargs -0 sed -i 's/example/mysuperplugin/g' # Change all occurrences of 'example' to your plugin name 'mysuperplugin'. find . -type f -print0 | xargs -0 sed -i 's/example/mysuperplugin/g' # Change all occurrences of 'example' to your plugin name 'mysuperplugin'.
mv templates/example templates/mysuperplugin # Rename templates folder. mv templates/example templates/mysuperplugin # Rename templates folder.
``` ```
- if you are on macOS and having difficulty with 'sed', consider `brew install gnu-sed` and use 'gsed', without -0 option after xargs. - if you are on macOS and having difficulty with 'sed', consider `brew install gnu-sed` and use 'gsed', without -0 option after xargs.
1. Edit `manifest.json` and change the organisation name to your GitHub username. 1. Edit `manifest.json` and change the organisation name to your GitHub username.
@@ -30,17 +30,15 @@ mv templates/example templates/mysuperplugin # Rename templates folder.
1. ... 1. ...
1. Profit!!! 1. Profit!!!
Extension structure explained ## Extension structure explained
-----------------------------
* views_api.py: This is where your public API would go. It will be exposed at "$DOMAIN/$PLUGIN/$ROUTE". For example: https://lnbits.com/mysuperplugin/api/v1/tools. - views_api.py: This is where your public API would go. It will be exposed at "$DOMAIN/$PLUGIN/$ROUTE". For example: https://lnbits.com/mysuperplugin/api/v1/tools.
* views.py: The `/` path will show up as your plugin's home page in lnbits' UI. Other pages you can define yourself. The `templates` folder should explain itself in relation to this. - views.py: The `/` path will show up as your plugin's home page in lnbits' UI. Other pages you can define yourself. The `templates` folder should explain itself in relation to this.
* migrations.py: Create database tables for your plugin. They'll be created automatically when you start lnbits. - migrations.py: Create database tables for your plugin. They'll be created automatically when you start lnbits.
... This document is a work-in-progress. Send pull requests if you get stuck, so others don't. ... This document is a work-in-progress. Send pull requests if you get stuck, so others don't.
## Adding new dependencies
Adding new dependencies
-----------------------
DO NOT ADD NEW DEPENDENCIES. Try to use the dependencies that are available in `pyproject.toml`. Getting the LNbits project to accept a new dependency is time consuming and uncertain, and may result in your extension NOT being made available to others. DO NOT ADD NEW DEPENDENCIES. Try to use the dependencies that are available in `pyproject.toml`. Getting the LNbits project to accept a new dependency is time consuming and uncertain, and may result in your extension NOT being made available to others.
@@ -53,9 +51,7 @@ $ poetry add <package>
**But we need an extra step to make sure LNbits doesn't break in production.** **But we need an extra step to make sure LNbits doesn't break in production.**
Dependencies need to be added to `pyproject.toml`, then tested by running on `poetry` compatibility can be tested with `nix build .#checks.x86_64-linux.vmTest`. Dependencies need to be added to `pyproject.toml`, then tested by running on `poetry` compatibility can be tested with `nix build .#checks.x86_64-linux.vmTest`.
## SQLite to PostgreSQL migration
SQLite to PostgreSQL migration
-----------------------
LNbits currently supports SQLite and PostgreSQL databases. There is a migration script `tools/conv.py` that helps users migrate from SQLite to PostgreSQL. This script also copies all extension databases to the new backend. LNbits currently supports SQLite and PostgreSQL databases. There is a migration script `tools/conv.py` that helps users migrate from SQLite to PostgreSQL. This script also copies all extension databases to the new backend.
@@ -64,22 +60,31 @@ LNbits currently supports SQLite and PostgreSQL databases. There is a migration
`mock_data.zip` contains a few lines of sample SQLite data and is used in automated GitHub test to see whether your migration in `conv.py` works. Run your extension and save a few lines of data into a SQLite `your_extension.sqlite3` file. Unzip `tests/data/mock_data.zip`, add `your_extension.sqlite3`, updated `database.sqlite3` and zip it again. Add the updated `mock_data.zip` to your PR. `mock_data.zip` contains a few lines of sample SQLite data and is used in automated GitHub test to see whether your migration in `conv.py` works. Run your extension and save a few lines of data into a SQLite `your_extension.sqlite3` file. Unzip `tests/data/mock_data.zip`, add `your_extension.sqlite3`, updated `database.sqlite3` and zip it again. Add the updated `mock_data.zip` to your PR.
### running migration locally ### running migration locally
you will need a running postgres database you will need a running postgres database
#### create lnbits user for migration database #### create lnbits user for migration database
```console ```console
sudo su - postgres -c "psql -c 'CREATE ROLE lnbits LOGIN PASSWORD 'lnbits';'" sudo su - postgres -c "psql -c 'CREATE ROLE lnbits LOGIN PASSWORD 'lnbits';'"
``` ```
#### create migration database #### create migration database
```console ```console
sudo su - postgres -c "psql -c 'CREATE DATABASE migration;'" sudo su - postgres -c "psql -c 'CREATE DATABASE migration;'"
``` ```
#### run the migration #### run the migration
```console ```console
make test-migration make test-migration
``` ```
sudo su - postgres -c "psql -c 'CREATE ROLE lnbits LOGIN PASSWORD 'lnbits';'" sudo su - postgres -c "psql -c 'CREATE ROLE lnbits LOGIN PASSWORD 'lnbits';'"
#### clean migration database afterwards, fails if you try again #### clean migration database afterwards, fails if you try again
```console ```console
sudo su - postgres -c "psql -c 'DROP DATABASE IF EXISTS migration;'" sudo su - postgres -c "psql -c 'DROP DATABASE IF EXISTS migration;'"
``` ```
+30 -27
View File
@@ -1,29 +1,32 @@
<html> <html>
<head> <head>
<!-- Load the latest Swagger UI code and style from npm using unpkg.com --> <!-- Load the latest Swagger UI code and style from npm using unpkg.com -->
<script src="https://unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script> <script src="https://unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
<link rel="stylesheet" type="text/css" href="https://unpkg.com/swagger-ui-dist@3/swagger-ui.css"/> <link
<title>My New API</title> rel="stylesheet"
</head> type="text/css"
<body> href="https://unpkg.com/swagger-ui-dist@3/swagger-ui.css"
<div id="swagger-ui"></div> <!-- Div to hold the UI component --> />
<script> <title>My New API</title>
window.onload = function () { </head>
// Begin Swagger UI call region <body>
const ui = SwaggerUIBundle({ <div id="swagger-ui"></div>
url: "https://legend.lnbits.com/openapi.json", //Location of Open API spec in the repo <!-- Div to hold the UI component -->
dom_id: '#swagger-ui', <script>
deepLinking: true, window.onload = function () {
presets: [ // Begin Swagger UI call region
SwaggerUIBundle.presets.apis, const ui = SwaggerUIBundle({
SwaggerUIBundle.SwaggerUIStandalonePreset url: 'https://demo.lnbits.com/openapi.json', //Location of Open API spec in the repo
], dom_id: '#swagger-ui',
plugins: [ deepLinking: true,
SwaggerUIBundle.plugins.DownloadUrl presets: [
], SwaggerUIBundle.presets.apis,
}) SwaggerUIBundle.SwaggerUIStandalonePreset
window.ui = ui ],
} plugins: [SwaggerUIBundle.plugins.DownloadUrl]
</script> })
</body> window.ui = ui
}
</script>
</body>
</html> </html>
+2 -5
View File
@@ -5,14 +5,11 @@ title: Websockets
nav_order: 2 nav_order: 2
--- ---
# Websockets
Websockets
=================
`websockets` are a great way to add a two way instant data channel between server and client. `websockets` are a great way to add a two way instant data channel between server and client.
LNbits has a useful in built websocket tool. With a websocket client connect to (obv change `somespecificid`) `wss://legend.lnbits.com/api/v1/ws/somespecificid` (you can use an online websocket tester). Now make a get to `https://legend.lnbits.com/api/v1/ws/somespecificid/somedata`. You can send data to that websocket by using `from lnbits.core.services import websocketUpdater` and the function `websocketUpdater("somespecificid", "somdata")`. LNbits has a useful in built websocket tool. With a websocket client connect to (obv change `somespecificid`) `wss://demo.lnbits.com/api/v1/ws/somespecificid` (you can use an online websocket tester). Now make a get to `https://demo.lnbits.com/api/v1/ws/somespecificid/somedata`. You can send data to that websocket by using `from lnbits.core.services import websocketUpdater` and the function `websocketUpdater("somespecificid", "somdata")`.
Example vue-js function for listening to the websocket: Example vue-js function for listening to the websocket:
+14 -12
View File
@@ -4,17 +4,15 @@ title: Admin UI
nav_order: 4 nav_order: 4
--- ---
# Admin UI
Admin UI
========
The LNbits Admin UI lets you change LNbits settings via the LNbits frontend. The LNbits Admin UI lets you change LNbits settings via the LNbits frontend.
It is disabled by default and the first time you set the environment variable `LNBITS_ADMIN_UI=true` It is disabled by default and the first time you set the environment variable `LNBITS_ADMIN_UI=true`
the settings are initialized and saved to the database and will be used from there as long the UI is enabled. the settings are initialized and saved to the database and will be used from there as long the UI is enabled.
From there on the settings from the database are used. From there on the settings from the database are used.
# Super User
Super User
==========
With the Admin UI we introduced the super user, it is created with the initialisation of the Admin UI and will be shown with a success message in the server logs. With the Admin UI we introduced the super user, it is created with the initialisation of the Admin UI and will be shown with a success message in the server logs.
The super user has access to the server and can change settings that may crash the server and make it unresponsive via the frontend and api, like changing funding sources. The super user has access to the server and can change settings that may crash the server and make it unresponsive via the frontend and api, like changing funding sources.
@@ -29,48 +27,52 @@ We also added a decorator for the API routes to check for super user.
There is also the possibility of posting the super user via webhook to another service when it is created. you can look it up here https://github.com/lnbits/lnbits/blob/main/lnbits/settings.py `class SaaSSettings` There is also the possibility of posting the super user via webhook to another service when it is created. you can look it up here https://github.com/lnbits/lnbits/blob/main/lnbits/settings.py `class SaaSSettings`
# Admin Users
Admin Users
===========
environment variable: `LNBITS_ADMIN_USERS`, comma-separated list of user ids environment variable: `LNBITS_ADMIN_USERS`, comma-separated list of user ids
Admin Users can change settings in the admin ui as well, with the exception of funding source settings, because they require e server restart and could potentially make the server inaccessible. Also they have access to all the extension defined in `LNBITS_ADMIN_EXTENSIONS`. Admin Users can change settings in the admin ui as well, with the exception of funding source settings, because they require e server restart and could potentially make the server inaccessible. Also they have access to all the extension defined in `LNBITS_ADMIN_EXTENSIONS`.
# Allowed Users
Allowed Users
=============
environment variable: `LNBITS_ALLOWED_USERS`, comma-separated list of user ids environment variable: `LNBITS_ALLOWED_USERS`, comma-separated list of user ids
By defining this users, LNbits will no longer be usable by the public, only defined users and admins can then access the LNbits frontend. By defining this users, LNbits will no longer be usable by the public, only defined users and admins can then access the LNbits frontend.
Setting this environment variable also disables account creation. Setting this environment variable also disables account creation.
Account creation can be also disabled by setting `LNBITS_ALLOW_NEW_ACCOUNTS=false` Account creation can be also disabled by setting `LNBITS_ALLOW_NEW_ACCOUNTS=false`
# How to activate
How to activate
=============
``` ```
$ sudo systemctl stop lnbits.service $ sudo systemctl stop lnbits.service
$ cd ~/lnbits-legend $ cd ~/lnbits
$ sudo nano .env $ sudo nano .env
``` ```
-> set: `LNBITS_ADMIN_UI=true` -> set: `LNBITS_ADMIN_UI=true`
Now start LNbits once in the terminal window Now start LNbits once in the terminal window
``` ```
$ poetry run lnbits $ poetry run lnbits
``` ```
You can now `cat` the Super User ID: You can now `cat` the Super User ID:
``` ```
$ cat data/.super_user $ cat data/.super_user
123de4bfdddddbbeb48c8bc8382fe123 123de4bfdddddbbeb48c8bc8382fe123
``` ```
You can access your super user account at `/wallet?usr=super_user_id`. You just have to append it to your normal LNbits web domain. You can access your super user account at `/wallet?usr=super_user_id`. You just have to append it to your normal LNbits web domain.
After that you will find the __`Admin` / `Manage Server`__ between `Wallets` and `Extensions` After that you will find the **`Admin` / `Manage Server`** between `Wallets` and `Extensions`
Here you can design the interface, it has TOPUP to fill wallets and you can restrict access rights to extensions only for admins or generally deactivated for everyone. You can make users admins or set up Allowed Users if you want to restrict access. And of course the classic settings of the .env file, e.g. to change the funding source wallet or set a charge fee. Here you can design the interface, it has TOPUP to fill wallets and you can restrict access rights to extensions only for admins or generally deactivated for everyone. You can make users admins or set up Allowed Users if you want to restrict access. And of course the classic settings of the .env file, e.g. to change the funding source wallet or set a charge fee.
Do not forget Do not forget
``` ```
sudo systemctl start lnbits.service sudo systemctl start lnbits.service
``` ```
A little hint, if you set `RESET TO DEFAULTS`, then a new Super User Account will also be created. The old one is then no longer valid. A little hint, if you set `RESET TO DEFAULTS`, then a new Super User Account will also be created. The old one is then no longer valid.
+32 -31
View File
@@ -10,16 +10,16 @@ Go to `Manage Server` > `Server` > `Extensions Manifests`
![image](https://user-images.githubusercontent.com/2951406/213494038-e8152d8e-61f2-4cb7-8b5f-361fc3f9a31f.png) ![image](https://user-images.githubusercontent.com/2951406/213494038-e8152d8e-61f2-4cb7-8b5f-361fc3f9a31f.png)
An `Extension Manifest` is a link to a `JSON` file which contains information about various extensions that can be installed (repository of extensions). An `Extension Manifest` is a link to a `JSON` file which contains information about various extensions that can be installed (repository of extensions).
Multiple repositories can be configured. For more information check the [Manifest File](https://github.com/lnbits/lnbits/blob/main/docs/guide/extension-install.md#manifest-file) section. Multiple repositories can be configured. For more information check the [Manifest File](https://github.com/lnbits/lnbits/blob/main/docs/guide/extension-install.md#manifest-file) section.
**LNbits** administrators should configure their instances to use repositories that they trust (like the [lnbits-extensions](https://github.com/lnbits/lnbits-extensions/) one). **LNbits** administrators should configure their instances to use repositories that they trust (like the [lnbits-extensions](https://github.com/lnbits/lnbits-extensions/) one).
> **Warning** > **Warning**
> Extensions can have bugs or malicious code, be careful what you install!! > Extensions can have bugs or malicious code, be careful what you install!!
## Install New Extension ## Install New Extension
Only administrator users can install or upgrade extensions. Only administrator users can install or upgrade extensions.
Go to `Manage Extensions` > `Add Remove Extensions` Go to `Manage Extensions` > `Add Remove Extensions`
@@ -45,13 +45,12 @@ Select the version to be installed (usually the last one) and click `Install`. O
> >
> For Explicit Release: the order of the releases is the one in the "extensions" object > For Explicit Release: the order of the releases is the one in the "extensions" object
The extension has been installed but it cannot be accessed yet. In order to activate the extension toggle it in the `Activated` state. The extension has been installed but it cannot be accessed yet. In order to activate the extension toggle it in the `Activated` state.
Go to `Manage Extensions` (as admin user or regular user). Search for the extension and enable it. Go to `Manage Extensions` (as admin user or regular user). Search for the extension and enable it.
## Uninstall Extension ## Uninstall Extension
On the `Install` page click `Manage` for the extension you want to uninstall: On the `Install` page click `Manage` for the extension you want to uninstall:
![image](https://user-images.githubusercontent.com/2951406/213653194-32cbb1da-dcc8-43cf-8a82-1ec5d2d3dc16.png) ![image](https://user-images.githubusercontent.com/2951406/213653194-32cbb1da-dcc8-43cf-8a82-1ec5d2d3dc16.png)
@@ -65,6 +64,7 @@ Users will no longer be able to access the extension.
> The database for the extension is not removed. If the extension is re-installed later, the data will be accessible. > The database for the extension is not removed. If the extension is re-installed later, the data will be accessible.
## Manifest File ## Manifest File
The manifest file is just a `JSON` file that lists a collection of extensions that can be installed. This file is of the form: The manifest file is just a `JSON` file that lists a collection of extensions that can be installed. This file is of the form:
```json ```json
@@ -77,30 +77,32 @@ The manifest file is just a `JSON` file that lists a collection of extensions th
There are two ways to specify installable extensions: There are two ways to specify installable extensions:
### Explicit Release ### Explicit Release
It goes under the `extensions` object and it is of the form: It goes under the `extensions` object and it is of the form:
```json ```json
{ {
"id": "lnurlp", "id": "lnurlp",
"name": "LNURL Pay Links", "name": "LNURL Pay Links",
"version": 1, "version": 1,
"shortDescription": "Upgrade to version 111111111", "shortDescription": "Upgrade to version 111111111",
"icon": "receipt", "icon": "receipt",
"details": "All charge names should be <code>111111111</code>. API panel must show: <br>", "details": "All charge names should be <code>111111111</code>. API panel must show: <br>",
"archive": "https://github.com/lnbits/lnbits-extensions/raw/main/new/lnurlp/1/lnurlp.zip", "archive": "https://github.com/lnbits/lnbits-extensions/raw/main/new/lnurlp/1/lnurlp.zip",
"hash": "a22d02de6bf306a7a504cd344e032cc6d48837a1d4aeb569a55a57507bf9a43a", "hash": "a22d02de6bf306a7a504cd344e032cc6d48837a1d4aeb569a55a57507bf9a43a",
"htmlUrl": "https://github.com/lnbits/lnbits-extensions/tree/main/new/lnurlp/1", "htmlUrl": "https://github.com/lnbits/lnbits-extensions/tree/main/new/lnurlp/1",
"infoNotification": "This is a very old version", "infoNotification": "This is a very old version",
"dependencies": ["other-ext-id"] "dependencies": ["other-ext-id"]
} }
``` ```
<details><summary>Fields Detailed Description</summary> <details><summary>Fields Detailed Description</summary>
| Field | Type | | Description | | Field | Type | | Description |
|----------------------|---------------|-----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | -------------------- | ------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| id | string | mandatory | The ID of the extension. Must be unique for each extension. It is also used as the path in the URL. | | id | string | mandatory | The ID of the extension. Must be unique for each extension. It is also used as the path in the URL. |
| name | string | mandatory | User friendly name for the extension. It will be displayed on the installation page. | | name | string | mandatory | User friendly name for the extension. It will be displayed on the installation page. |
| version | string | mandatory | Version of this release. [Semantic versioning](https://semver.org/) is recommended. | | version | string | mandatory | Version of this release. [Semantic versioning](https://semver.org/) is recommended. |
| shortDescription | string | optional | A few words about the extension. It will be displayed on the installation page. | | shortDescription | string | optional | A few words about the extension. It will be displayed on the installation page. |
| icon | string | optional | quasar valid icon name | | icon | string | optional | quasar valid icon name |
| details | string (html) | optional | Details about this particular release | | details | string (html) | optional | Details about this particular release |
@@ -109,31 +111,30 @@ It goes under the `extensions` object and it is of the form:
| htmlUrl | string | optional | Link to the extension home page. | | htmlUrl | string | optional | Link to the extension home page. |
| infoNotification | string | optional | Users that have this release installed will see a info message for their extension. For example if the extension support will be terminated soon. | | infoNotification | string | optional | Users that have this release installed will see a info message for their extension. For example if the extension support will be terminated soon. |
| criticalNotification | string | optional | Reserved for urgent notifications. The admin user will receive a message each time it visits the `Install` page. One example is if the extension has a critical bug. | | criticalNotification | string | optional | Reserved for urgent notifications. The admin user will receive a message each time it visits the `Install` page. One example is if the extension has a critical bug. |
| dependencies | list | optional | A list of extension IDs. It signals that those extensions must be installed BEFORE the this one can be installed. | dependencies | list | optional | A list of extension IDs. It signals that those extensions must be installed BEFORE the this one can be installed. |
</details> </details>
This mode has the advantage of strictly specifying what releases of an extension can be installed. This mode has the advantage of strictly specifying what releases of an extension can be installed.
### GitHub Repository ### GitHub Repository
It goes under the `repos` object and it is of the form: It goes under the `repos` object and it is of the form:
```json ```json
{ {
"id": "withdraw", "id": "withdraw",
"organisation": "lnbits", "organisation": "lnbits",
"repository": "withdraw-extension" "repository": "withdraw-extension"
} }
``` ```
| Field | Type | Description | | Field | Type | Description |
|--------------|--------|-------------------------------------------------------| | ------------ | ------ | --------------------------------------------------------------------------------------------------- |
| id | string | The ID of the extension. Must be unique for each extension. It is also used as the path in the URL. | | id | string | The ID of the extension. Must be unique for each extension. It is also used as the path in the URL. |
| organisation | string | The GitHub organisation (eg: `lnbits`) | | organisation | string | The GitHub organisation (eg: `lnbits`) |
| repository | string | The GitHub repository name (eg: `withdraw-extension`) | | repository | string | The GitHub repository name (eg: `withdraw-extension`) |
The admin user will see all releases from the Github repository: The admin user will see all releases from the Github repository:
![image](https://user-images.githubusercontent.com/2951406/213508934-11de5ae5-2045-471c-854b-94b6acbf4434.png) ![image](https://user-images.githubusercontent.com/2951406/213508934-11de5ae5-2045-471c-854b-94b6acbf4434.png)
+6 -3
View File
@@ -4,10 +4,10 @@ title: FAQ
nav_order: 5 nav_order: 5
--- ---
# FAQ - Frequently Asked Questions # FAQ - Frequently Asked Questions
## Install options ## Install options
<ul><p>LNbits is not a node management software but a ⚡️LN only accounting system on top of a funding source.</p> <ul><p>LNbits is not a node management software but a ⚡️LN only accounting system on top of a funding source.</p>
<details><summary>Funding my LNbits wallet from my node it doesn't work.</summary> <details><summary>Funding my LNbits wallet from my node it doesn't work.</summary>
@@ -54,6 +54,7 @@ allow-self-payment=1
</ul> </ul>
## Troubleshooting ## Troubleshooting
<ul><details><summary>Message "https error" or network error" when scanning a LNbits QR</summary> <ul><details><summary>Message "https error" or network error" when scanning a LNbits QR</summary>
<p>Bad news, this is a routing error that might have quite a lot of reasons. Let´s try a few of the most possible problems and their solutions. First choose your setup</p> <p>Bad news, this is a routing error that might have quite a lot of reasons. Let´s try a few of the most possible problems and their solutions. First choose your setup</p>
<ul> <ul>
@@ -83,7 +84,7 @@ allow-self-payment=1
<details><summary>Wallet-URL deleted, are my funds safu ?</summary> <details><summary>Wallet-URL deleted, are my funds safu ?</summary>
<ul> <ul>
<li> <li>
<details><summary>Wallet on demo server legend.lnbits</summary> <details><summary>Wallet on demo server demo.lnbits.com</summary>
<p>Always save a copy of your wallet-URL, Export2phone-QR or LNDhub for your own wallets in a safe place. LNbits CANNOT help you to recover them when lost.</p> <p>Always save a copy of your wallet-URL, Export2phone-QR or LNDhub for your own wallets in a safe place. LNbits CANNOT help you to recover them when lost.</p>
</details> </details>
</li> </li>
@@ -155,7 +156,6 @@ allow-self-payment=1
</p> </p>
</details> </details>
<details><summary>How can I use a LNbits lndhub account in other wallet apps?</summary> <details><summary>How can I use a LNbits lndhub account in other wallet apps?</summary>
<p>Open your LNbits with the account / wallet you want to use, go to "manage extensions" and activate the <a href="https://github.com/lnbits/lndhub">LNDHUB extension</a>.</p> <p>Open your LNbits with the account / wallet you want to use, go to "manage extensions" and activate the <a href="https://github.com/lnbits/lndhub">LNDHUB extension</a>.</p>
<p>Then open the LNDHUB extension, choose the wallet you want to use and scan the QR code you want to use: "admin" or "invoice only", depending on the security level you want for that wallet.</p> <p>Then open the LNDHUB extension, choose the wallet you want to use and scan the QR code you want to use: "admin" or "invoice only", depending on the security level you want for that wallet.</p>
@@ -166,6 +166,7 @@ allow-self-payment=1
</ul> </ul>
## Building hardware tools ## Building hardware tools
<ul> <p>LNbits has all sorts of open APIs and tools to program and connect to a lot of different devices for a gazillion of use-cases. Let us know what you did with it ! Come to the <a href="https://t.me/makerbits">Makerbits Telegram Group</a> if you are interested in building or if you need help with a project - we got you!</p> <ul> <p>LNbits has all sorts of open APIs and tools to program and connect to a lot of different devices for a gazillion of use-cases. Let us know what you did with it ! Come to the <a href="https://t.me/makerbits">Makerbits Telegram Group</a> if you are interested in building or if you need help with a project - we got you!</p>
<details><summary>ATM - deposit and withdraw in your shop or at your meetup</summary> <details><summary>ATM - deposit and withdraw in your shop or at your meetup</summary>
@@ -216,6 +217,7 @@ allow-self-payment=1
</ul> </ul>
## Use cases of LNbits ## Use cases of LNbits
<ul><details><summary>Merchant</summary> <ul><details><summary>Merchant</summary>
<p>LNbits is a powerful solution for merchants, due to the easy setup with various extensions, that can be used for many scenarios.</p> <p>LNbits is a powerful solution for merchants, due to the easy setup with various extensions, that can be used for many scenarios.</p>
<p><a href="https://darthcoin.substack.com/p/lnbits-for-small-merchants">Here is an overview of the LNbits tools available for a small restaurant as well as a hotel</a></p> <p><a href="https://darthcoin.substack.com/p/lnbits-for-small-merchants">Here is an overview of the LNbits tools available for a small restaurant as well as a hotel</a></p>
@@ -262,6 +264,7 @@ allow-self-payment=1
</ul> </ul>
## Developing for LNbits ## Developing for LNbits
<ul> <ul>
<li><a href="https://docs.lnbits.org/devs/development.html">Making extensions / How to use Websockets / API reference</a></li> <li><a href="https://docs.lnbits.org/devs/development.html">Making extensions / How to use Websockets / API reference</a></li>
<li><a href="https://t.me/lnbits">Telegram LNbits Support Group</a></li></ul> <li><a href="https://t.me/lnbits">Telegram LNbits Support Group</a></li></ul>
+24 -4
View File
@@ -1,19 +1,23 @@
## Defining a route with path parameters ## Defining a route with path parameters
**old:** **old:**
```python ```python
# with <> # with <>
@offlineshop_ext.route("/lnurl/<item_id>", methods=["GET"]) @offlineshop_ext.route("/lnurl/<item_id>", methods=["GET"])
``` ```
**new:** **new:**
```python ```python
# with curly braces: {} # with curly braces: {}
@offlineshop_ext.get("/lnurl/{item_id}") @offlineshop_ext.get("/lnurl/{item_id}")
``` ```
## Check if a user exists and access user object ## Check if a user exists and access user object
**old:** **old:**
```python ```python
# decorators # decorators
@check_user_exists() @check_user_exists()
@@ -24,14 +28,18 @@ async def do_routing_stuff():
**new:** **new:**
If user doesn't exist, `Depends(check_user_exists)` will raise an exception. If user doesn't exist, `Depends(check_user_exists)` will raise an exception.
If user exists, `user` will be the user object If user exists, `user` will be the user object
```python ```python
# depends calls # depends calls
@core_html_routes.get("/my_route") @core_html_routes.get("/my_route")
async def extensions(user: User = Depends(check_user_exists)): async def extensions(user: User = Depends(check_user_exists)):
pass pass
``` ```
## Returning data from API calls ## Returning data from API calls
**old:** **old:**
```python ```python
return ( return (
{ {
@@ -42,9 +50,11 @@ return (
HTTPStatus.OK, HTTPStatus.OK,
) )
``` ```
FastAPI returns `HTTPStatus.OK` by default id no Exception is raised FastAPI returns `HTTPStatus.OK` by default id no Exception is raised
**new:** **new:**
```python ```python
return { return {
"id": wallet.wallet.id, "id": wallet.wallet.id,
@@ -54,6 +64,7 @@ return {
``` ```
To change the default HTTPStatus, add it to the path decorator To change the default HTTPStatus, add it to the path decorator
```python ```python
@core_app.post("/api/v1/payments", status_code=HTTPStatus.CREATED) @core_app.post("/api/v1/payments", status_code=HTTPStatus.CREATED)
async def payments(): async def payments():
@@ -61,7 +72,9 @@ async def payments():
``` ```
## Raise exceptions ## Raise exceptions
**old:** **old:**
```python ```python
return ( return (
{"message": f"Failed to connect to {domain}."}, {"message": f"Failed to connect to {domain}."},
@@ -74,6 +87,7 @@ abort(HTTPStatus.INTERNAL_SERVER_ERROR, "Could not process withdraw LNURL.")
**new:** **new:**
Raise an exception to return a status code other than the default status code. Raise an exception to return a status code other than the default status code.
```python ```python
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, status_code=HTTPStatus.BAD_REQUEST,
@@ -82,7 +96,9 @@ raise HTTPException(
``` ```
## Extensions ## Extensions
**old:** **old:**
```python ```python
from quart import Blueprint from quart import Blueprint
@@ -92,6 +108,7 @@ amilk_ext: Blueprint = Blueprint(
``` ```
**new:** **new:**
```python ```python
from fastapi import APIRouter from fastapi import APIRouter
from lnbits.jinja2_templating import Jinja2Templates from lnbits.jinja2_templating import Jinja2Templates
@@ -114,9 +131,12 @@ offlineshop_rndr = template_renderer([
``` ```
## Possible optimizations ## Possible optimizations
### Use Redis as a cache server ### Use Redis as a cache server
Instead of hitting the database over and over again, we can store a short lived object in [Redis](https://redis.io) for an arbitrary key. Instead of hitting the database over and over again, we can store a short lived object in [Redis](https://redis.io) for an arbitrary key.
Example: Example:
* Get transactions for a wallet ID
* User data for a user id - Get transactions for a wallet ID
* Wallet data for a Admin / Invoice key - User data for a user id
- Wallet data for a Admin / Invoice key
+20 -8
View File
@@ -16,6 +16,7 @@ Mininum poetry version has is ^1.2, but it is recommended to use latest poetry.
Make sure you have Python 3.9 or 3.10 installed. Make sure you have Python 3.9 or 3.10 installed.
### install python on ubuntu ### install python on ubuntu
```sh ```sh
# for making sure python 3.9 is installed, skip if installed. To check your installed version: python3 --version # for making sure python 3.9 is installed, skip if installed. To check your installed version: python3 --version
sudo apt update sudo apt update
@@ -25,6 +26,7 @@ sudo apt install python3.9 python3.9-distutils
``` ```
### install poetry ### install poetry
```sh ```sh
curl -sSL https://install.python-poetry.org | python3 - curl -sSL https://install.python-poetry.org | python3 -
# Once the above poetry install is completed, use the installation path printed to terminal and replace in the following command # Once the above poetry install is completed, use the installation path printed to terminal and replace in the following command
@@ -56,6 +58,7 @@ poetry run lnbits
# adding --debug in the start-up command above to help your troubleshooting and generate a more verbose output # adding --debug in the start-up command above to help your troubleshooting and generate a more verbose output
# Note that you have to add the line DEBUG=true in your .env file, too. # Note that you have to add the line DEBUG=true in your .env file, too.
``` ```
#### Updating the server #### Updating the server
``` ```
@@ -97,7 +100,7 @@ nix run
Ideally you would set the environment via the `.env` file, Ideally you would set the environment via the `.env` file,
but you can also set the env variables or pass command line arguments: but you can also set the env variables or pass command line arguments:
``` sh ```sh
# .env variables are currently passed when running, but LNbits can be managed with the admin UI. # .env variables are currently passed when running, but LNbits can be managed with the admin UI.
LNBITS_ADMIN_UI=true ./result/bin/lnbits --port 9000 LNBITS_ADMIN_UI=true ./result/bin/lnbits --port 9000
@@ -108,13 +111,16 @@ SUPER_USER=be54db7f245346c8833eaa430e1e0405 LNBITS_ADMIN_UI=true ./result/bin/ln
## Option 3: Docker ## Option 3: Docker
use latest version from docker hub use latest version from docker hub
```sh ```sh
docker pull lnbits/lnbits docker pull lnbits/lnbits
wget https://raw.githubusercontent.com/lnbits/lnbits/main/.env.example -O .env wget https://raw.githubusercontent.com/lnbits/lnbits/main/.env.example -O .env
mkdir data mkdir data
docker run --detach --publish 5000:5000 --name lnbits --volume ${PWD}/.env:/app/.env --volume ${PWD}/data/:/app/data lnbits/lnbits docker run --detach --publish 5000:5000 --name lnbits --volume ${PWD}/.env:/app/.env --volume ${PWD}/data/:/app/data lnbits/lnbits
``` ```
build the image yourself build the image yourself
```sh ```sh
git clone https://github.com/lnbits/lnbits.git git clone https://github.com/lnbits/lnbits.git
cd lnbits cd lnbits
@@ -157,7 +163,7 @@ You'll be prompted to enter an app name, region, postgres (choose no), deploy no
You'll now find a file in the directory called `fly.toml`. Open that file and modify/add the following settings. You'll now find a file in the directory called `fly.toml`. Open that file and modify/add the following settings.
Note: Be sure to replace `${PUT_YOUR_LNBITS_ENV_VARS_HERE}` with all relevant environment variables in `.env` or `.env.example`. Environment variable strings should be quoted here, so if in `.env` you have `LNBITS_ENDPOINT=https://legend.lnbits.com` in `fly.toml` you should have `LNBITS_ENDPOINT="https://legend.lnbits.com"`. Note: Be sure to replace `${PUT_YOUR_LNBITS_ENV_VARS_HERE}` with all relevant environment variables in `.env` or `.env.example`. Environment variable strings should be quoted here, so if in `.env` you have `LNBITS_ENDPOINT=https://demo.lnbits.com` in `fly.toml` you should have `LNBITS_ENDPOINT="https://demo.lnbits.com"`.
Note: Don't enter secret environment variables here. Fly.io offers secrets (via the `fly secrets` command) that are exposed as environment variables in your runtime. So, for example, if using the LND_REST funding source, you can run `fly secrets set LND_REST_MACAROON=<hex_macaroon_data>`. Note: Don't enter secret environment variables here. Fly.io offers secrets (via the `fly secrets` command) that are exposed as environment variables in your runtime. So, for example, if using the LND_REST funding source, you can run `fly secrets set LND_REST_MACAROON=<hex_macaroon_data>`.
@@ -254,11 +260,10 @@ You might also need to install additional packages or perform additional setup s
Take a look at [Polar](https://lightningpolar.com/) for an excellent way of spinning up a Lightning Network dev environment. Take a look at [Polar](https://lightningpolar.com/) for an excellent way of spinning up a Lightning Network dev environment.
# Additional guides # Additional guides
## SQLite to PostgreSQL migration ## SQLite to PostgreSQL migration
If you already have LNbits installed and running, on an SQLite database, we **highly** recommend you migrate to postgres if you are planning to run LNbits on scale. If you already have LNbits installed and running, on an SQLite database, we **highly** recommend you migrate to postgres if you are planning to run LNbits on scale.
There's a script included that can do the migration easy. You should have Postgres already installed and there should be a password for the user (see Postgres install guide above). Additionally, your LNbits instance should run once on postgres to implement the database schema before the migration works: There's a script included that can do the migration easy. You should have Postgres already installed and there should be a password for the user (see Postgres install guide above). Additionally, your LNbits instance should run once on postgres to implement the database schema before the migration works:
@@ -280,7 +285,6 @@ make migration
Hopefully, everything works and get migrated... Launch LNbits again and check if everything is working properly. Hopefully, everything works and get migrated... Launch LNbits again and check if everything is working properly.
## LNbits as a systemd service ## LNbits as a systemd service
Systemd is great for taking care of your LNbits instance. It will start it on boot and restart it in case it crashes. If you want to run LNbits as a systemd service on your Debian/Ubuntu/Raspbian server, create a file at `/etc/systemd/system/lnbits.service` with the following content: Systemd is great for taking care of your LNbits instance. It will start it on boot and restart it in case it crashes. If you want to run LNbits as a systemd service on your Debian/Ubuntu/Raspbian server, create a file at `/etc/systemd/system/lnbits.service` with the following content:
@@ -457,28 +461,36 @@ service restart nginx
``` ```
## Using https without reverse proxy ## Using https without reverse proxy
The most common way of using LNbits via https is to use a reverse proxy such as Caddy, nginx, or ngriok. However, you can also run LNbits via https without additional software. This is useful for development purposes or if you want to use LNbits in your local network. The most common way of using LNbits via https is to use a reverse proxy such as Caddy, nginx, or ngriok. However, you can also run LNbits via https without additional software. This is useful for development purposes or if you want to use LNbits in your local network.
We have to create a self-signed certificate using `mkcert`. Note that this certificate is not "trusted" by most browsers but that's fine (since you know that you have created it) and encryption is always better than clear text. We have to create a self-signed certificate using `mkcert`. Note that this certificate is not "trusted" by most browsers but that's fine (since you know that you have created it) and encryption is always better than clear text.
#### Install mkcert #### Install mkcert
You can find the install instructions for `mkcert` [here](https://github.com/FiloSottile/mkcert). You can find the install instructions for `mkcert` [here](https://github.com/FiloSottile/mkcert).
Install mkcert on Ubuntu: Install mkcert on Ubuntu:
```sh ```sh
sudo apt install libnss3-tools sudo apt install libnss3-tools
curl -JLO "https://dl.filippo.io/mkcert/latest?for=linux/amd64" curl -JLO "https://dl.filippo.io/mkcert/latest?for=linux/amd64"
chmod +x mkcert-v*-linux-amd64 chmod +x mkcert-v*-linux-amd64
sudo cp mkcert-v*-linux-amd64 /usr/local/bin/mkcert sudo cp mkcert-v*-linux-amd64 /usr/local/bin/mkcert
``` ```
#### Create certificate #### Create certificate
To create a certificate, first `cd` into your LNbits folder and execute the following command on Linux: To create a certificate, first `cd` into your LNbits folder and execute the following command on Linux:
```sh ```sh
openssl req -new -newkey rsa:4096 -x509 -sha256 -days 3650 -nodes -out cert.pem -keyout key.pem openssl req -new -newkey rsa:4096 -x509 -sha256 -days 3650 -nodes -out cert.pem -keyout key.pem
``` ```
This will create two new files (`key.pem` and `cert.pem `). This will create two new files (`key.pem` and `cert.pem `).
Alternatively, you can use mkcert ([more info](https://kifarunix.com/how-to-create-self-signed-ssl-certificate-with-mkcert-on-ubuntu-18-04/)): Alternatively, you can use mkcert ([more info](https://kifarunix.com/how-to-create-self-signed-ssl-certificate-with-mkcert-on-ubuntu-18-04/)):
```sh ```sh
# add your local IP (192.x.x.x) as well if you want to use it in your local network # add your local IP (192.x.x.x) as well if you want to use it in your local network
mkcert localhost 127.0.0.1 ::1 mkcert localhost 127.0.0.1 ::1
@@ -490,7 +502,6 @@ You can then pass the certificate files to uvicorn when you start LNbits:
poetry run uvicorn lnbits.__main__:app --host 0.0.0.0 --port 5000 --ssl-keyfile ./key.pem --ssl-certfile ./cert.pem poetry run uvicorn lnbits.__main__:app --host 0.0.0.0 --port 5000 --ssl-keyfile ./key.pem --ssl-certfile ./cert.pem
``` ```
## LNbits running on Umbrel behind Tor ## LNbits running on Umbrel behind Tor
If you want to run LNbits on your Umbrel but want it to be reached through clearnet, _Uxellodunum_ made an extensive [guide](https://community.getumbrel.com/t/guide-lnbits-without-tor/604) on how to do it. If you want to run LNbits on your Umbrel but want it to be reached through clearnet, _Uxellodunum_ made an extensive [guide](https://community.getumbrel.com/t/guide-lnbits-without-tor/604) on how to do it.
@@ -502,7 +513,7 @@ To install using docker you first need to build the docker image as:
``` ```
git clone https://github.com/lnbits/lnbits.git git clone https://github.com/lnbits/lnbits.git
cd lnbits cd lnbits
docker build -t lnbits-legend . docker build -t lnbits/lnbits .
``` ```
You can launch the docker in a different directory, but make sure to copy `.env.example` from lnbits there You can launch the docker in a different directory, but make sure to copy `.env.example` from lnbits there
@@ -514,6 +525,7 @@ cp <lnbits_repo>/.env.example .env
and change the configuration in `.env` as required. and change the configuration in `.env` as required.
Then create the data directory Then create the data directory
``` ```
mkdir data mkdir data
``` ```
@@ -521,7 +533,7 @@ mkdir data
Then the image can be run as: Then the image can be run as:
``` ```
docker run --detach --publish 5000:5000 --name lnbits-legend -e "LNBITS_BACKEND_WALLET_CLASS='FakeWallet'" --volume ${PWD}/.env:/app/.env --volume ${PWD}/data/:/app/data lnbits-legend docker run --detach --publish 5000:5000 --name lnbits -e "LNBITS_BACKEND_WALLET_CLASS='FakeWallet'" --volume ${PWD}/.env:/app/.env --volume ${PWD}/data/:/app/data lnbits
``` ```
Finally you can access your lnbits on your machine at port 5000. Finally you can access your lnbits on your machine at port 5000.
+10 -4
View File
@@ -4,15 +4,12 @@ title: Backend wallets
nav_order: 3 nav_order: 3
--- ---
# Backend wallets
Backend wallets
===============
LNbits can run on top of many Lightning Network funding sources with more being added regularly. LNbits can run on top of many Lightning Network funding sources with more being added regularly.
A backend wallet can be configured using the following LNbits environment variables: A backend wallet can be configured using the following LNbits environment variables:
### CoreLightning ### CoreLightning
- `LNBITS_BACKEND_WALLET_CLASS`: **CoreLightningWallet** - `LNBITS_BACKEND_WALLET_CLASS`: **CoreLightningWallet**
@@ -95,6 +92,15 @@ For the invoice to work you must have a publicly accessible URL in your LNbits.
- `ZBD_API_ENDPOINT`: https://api.zebedee.io/v0/ - `ZBD_API_ENDPOINT`: https://api.zebedee.io/v0/
- `ZBD_API_KEY`: ZBDApiKey - `ZBD_API_KEY`: ZBDApiKey
### Phoenixd
For the invoice to work you must have a publicly accessible URL in your LNbits. You can get a phoenixd API key from the install
~/.phoenix/phoenix.conf, also see the documentation for phoenixd.
- `LNBITS_BACKEND_WALLET_CLASS`: **PhoenixdWallet**
- `PHOENIXD_API_ENDPOINT`: http://localhost:9740/
- `PHOENIXD_API_PASSWORD`: PhoenixdApiPassword
### Cliche Wallet ### Cliche Wallet
- `CLICHE_ENDPOINT`: ws://127.0.0.1:12000 - `CLICHE_ENDPOINT`: ws://127.0.0.1:12000
+7 -11
View File
@@ -4,21 +4,17 @@ title: Users Guide
nav_order: 1 nav_order: 1
--- ---
# LNbits, free and open-source Lightning Network wallet/accounts system
LNbits, free and open-source Lightning Network wallet/accounts system
=====================================================================
LNbits is a very simple Python application that sits on top of any funding source, and can be used as: LNbits is a very simple Python application that sits on top of any funding source, and can be used as:
* Accounts system to mitigate the risk of exposing applications to your full balance, via unique API keys for each wallet - Accounts system to mitigate the risk of exposing applications to your full balance, via unique API keys for each wallet
* Extendable platform for exploring Lightning Network functionality via LNbits extension framework - Extendable platform for exploring Lightning Network functionality via LNbits extension framework
* Part of a development stack via LNbits API - Part of a development stack via LNbits API
* Fallback wallet for the LNURL scheme - Fallback wallet for the LNURL scheme
* Instant wallet for LN demonstrations - Instant wallet for LN demonstrations
## LNbits as an account system
LNbits as an account system
---------------------------
LNbits is packaged with tools to help manage funds, such as a table of transactions, line chart of spending, LNbits is packaged with tools to help manage funds, such as a table of transactions, line chart of spending,
export to csv + more to come... export to csv + more to come...
+3
View File
@@ -40,6 +40,9 @@
pytest-md = prev.pytest-md.overridePythonAttrs ( pytest-md = prev.pytest-md.overridePythonAttrs (
old: { buildInputs = (old.buildInputs or []) ++ [ prev.setuptools ]; } old: { buildInputs = (old.buildInputs or []) ++ [ prev.setuptools ]; }
); );
types-mock = prev.pytest-md.overridePythonAttrs (
old: { buildInputs = (old.buildInputs or []) ++ [ prev.setuptools ]; }
);
}); });
}; };
}); });
+37 -226
View File
@@ -1,35 +1,28 @@
import asyncio import asyncio
import glob import glob
import importlib import importlib
import logging
import os import os
import shutil import shutil
import sys import sys
import traceback
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from hashlib import sha256
from http import HTTPStatus
from pathlib import Path from pathlib import Path
from typing import Callable, List, Optional from typing import Callable, List, Optional
from fastapi import FastAPI, HTTPException, Request from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from loguru import logger from loguru import logger
from slowapi import Limiter from slowapi import Limiter
from slowapi.util import get_remote_address from slowapi.util import get_remote_address
from starlette.middleware.sessions import SessionMiddleware from starlette.middleware.sessions import SessionMiddleware
from starlette.responses import JSONResponse
from lnbits.core.crud import get_dbversions, get_installed_extensions from lnbits.core.crud import get_dbversions, get_installed_extensions
from lnbits.core.helpers import migrate_extension_database from lnbits.core.helpers import migrate_extension_database
from lnbits.core.services import websocketUpdater
from lnbits.core.tasks import ( # watchdog_task from lnbits.core.tasks import ( # watchdog_task
killswitch_task, killswitch_task,
wait_for_paid_invoices, wait_for_paid_invoices,
) )
from lnbits.exceptions import register_exception_handlers
from lnbits.settings import settings from lnbits.settings import settings
from lnbits.tasks import ( from lnbits.tasks import (
cancel_all_tasks, cancel_all_tasks,
@@ -37,7 +30,12 @@ from lnbits.tasks import (
register_invoice_listener, register_invoice_listener,
) )
from lnbits.utils.cache import cache from lnbits.utils.cache import cache
from lnbits.wallets import get_wallet_class, set_wallet_class from lnbits.utils.logger import (
configure_logger,
initialize_server_websocket_logger,
log_server_info,
)
from lnbits.wallets import get_funding_source, set_funding_source
from .commands import migrate_databases from .commands import migrate_databases
from .core import init_core_routers from .core import init_core_routers
@@ -51,7 +49,6 @@ from .extension_manager import (
get_valid_extensions, get_valid_extensions,
version_parse, version_parse,
) )
from .helpers import template_renderer
from .middleware import ( from .middleware import (
CustomGZipMiddleware, CustomGZipMiddleware,
ExtensionsRedirectMiddleware, ExtensionsRedirectMiddleware,
@@ -69,6 +66,7 @@ from .tasks import (
async def startup(app: FastAPI): async def startup(app: FastAPI):
settings.lnbits_running = True
# wait till migration is done # wait till migration is done
await migrate_databases() await migrate_databases()
@@ -81,7 +79,7 @@ async def startup(app: FastAPI):
# initialize WALLET # initialize WALLET
try: try:
set_wallet_class() set_funding_source()
except Exception as e: except Exception as e:
logger.error(f"Error initializing {settings.lnbits_backend_wallet_class}: {e}") logger.error(f"Error initializing {settings.lnbits_backend_wallet_class}: {e}")
set_void_wallet_class() set_void_wallet_class()
@@ -97,21 +95,21 @@ async def startup(app: FastAPI):
await check_installed_extensions(app) await check_installed_extensions(app)
register_all_ext_routes(app) register_all_ext_routes(app)
if settings.lnbits_admin_ui:
initialize_server_logger()
# initialize tasks # initialize tasks
register_async_tasks() register_async_tasks()
async def shutdown(): async def shutdown():
logger.warning("LNbits shutting down...")
settings.lnbits_running = False
# shutdown event # shutdown event
cancel_all_tasks() cancel_all_tasks()
# wait a bit to allow them to finish, so that cleanup can run without problems # wait a bit to allow them to finish, so that cleanup can run without problems
await asyncio.sleep(0.1) await asyncio.sleep(0.1)
WALLET = get_wallet_class() funding_source = get_funding_source()
await WALLET.cleanup() await funding_source.cleanup()
@asynccontextmanager @asynccontextmanager
@@ -138,8 +136,8 @@ def create_app() -> FastAPI:
) )
# Allow registering new extensions routes without direct access to the `app` object # Allow registering new extensions routes without direct access to the `app` object
setattr(core_app_extra, "register_new_ext_routes", register_new_ext_routes(app)) core_app_extra.register_new_ext_routes = register_new_ext_routes(app)
setattr(core_app_extra, "register_new_ratelimiter", register_new_ratelimiter(app)) core_app_extra.register_new_ratelimiter = register_new_ratelimiter(app)
# register static files # register static files
static_path = Path("lnbits", "static") static_path = Path("lnbits", "static")
@@ -177,38 +175,39 @@ def create_app() -> FastAPI:
async def check_funding_source() -> None: async def check_funding_source() -> None:
funding_source = get_funding_source()
WALLET = get_wallet_class() max_retries = settings.funding_source_max_retries
sleep_time = 5
max_retries = 5
retry_counter = 0 retry_counter = 0
while True: while settings.lnbits_running:
try: try:
logger.info(f"Connecting to backend {WALLET.__class__.__name__}...") logger.info(f"Connecting to backend {funding_source.__class__.__name__}...")
error_message, balance = await WALLET.status() error_message, balance = await funding_source.status()
if not error_message: if not error_message:
retry_counter = 0 retry_counter = 0
logger.success( logger.success(
f"✔️ Backend {WALLET.__class__.__name__} connected " f"✔️ Backend {funding_source.__class__.__name__} connected "
f"and with a balance of {balance} msat." f"and with a balance of {balance} msat."
) )
break break
logger.error( logger.error(
f"The backend for {WALLET.__class__.__name__} isn't " f"The backend for {funding_source.__class__.__name__} isn't "
f"working properly: '{error_message}'", f"working properly: '{error_message}'",
RuntimeWarning, RuntimeWarning,
) )
except Exception as e: except Exception as e:
logger.error(f"Error connecting to {WALLET.__class__.__name__}: {e}") logger.error(
f"Error connecting to {funding_source.__class__.__name__}: {e}"
)
if retry_counter == max_retries: if retry_counter >= max_retries:
set_void_wallet_class() set_void_wallet_class()
WALLET = get_wallet_class() funding_source = get_funding_source()
break break
retry_counter += 1 retry_counter += 1
sleep_time = 0.25 * (2**retry_counter)
logger.warning( logger.warning(
f"Retrying connection to backend in {sleep_time} seconds... " f"Retrying connection to backend in {sleep_time} seconds... "
f"({retry_counter}/{max_retries})" f"({retry_counter}/{max_retries})"
@@ -221,7 +220,7 @@ def set_void_wallet_class():
"Fallback to VoidWallet, because the backend for " "Fallback to VoidWallet, because the backend for "
f"{settings.lnbits_backend_wallet_class} isn't working properly" f"{settings.lnbits_backend_wallet_class} isn't working properly"
) )
set_wallet_class("VoidWallet") set_funding_source("VoidWallet")
async def check_installed_extensions(app: FastAPI): async def check_installed_extensions(app: FastAPI):
@@ -300,7 +299,7 @@ async def check_installed_extension_files(ext: InstallableExtension) -> bool:
zip_files = glob.glob(os.path.join(settings.lnbits_data_folder, "zips", "*.zip")) zip_files = glob.glob(os.path.join(settings.lnbits_data_folder, "zips", "*.zip"))
if f"./{str(ext.zip_path)}" not in zip_files: if f"./{ext.zip_path!s}" not in zip_files:
await ext.download_archive() await ext.download_archive()
ext.extract_archive() ext.extract_archive()
@@ -403,54 +402,7 @@ def register_all_ext_routes(app: FastAPI):
try: try:
register_ext_routes(app, ext) register_ext_routes(app, ext)
except Exception as e: except Exception as e:
logger.error(f"Could not load extension `{ext.code}`: {str(e)}") logger.error(f"Could not load extension `{ext.code}`: {e!s}")
def initialize_server_logger():
super_user_hash = sha256(settings.super_user.encode("utf-8")).hexdigest()
serverlog_queue = asyncio.Queue()
async def update_websocket_serverlog():
while True:
msg = await serverlog_queue.get()
await websocketUpdater(super_user_hash, msg)
create_permanent_task(update_websocket_serverlog)
logger.add(
lambda msg: serverlog_queue.put_nowait(msg),
format=Formatter().format,
)
def log_server_info():
logger.info("Starting LNbits")
logger.info(f"Version: {settings.version}")
logger.info(f"Baseurl: {settings.lnbits_baseurl}")
logger.info(f"Host: {settings.host}")
logger.info(f"Port: {settings.port}")
logger.info(f"Debug: {settings.debug}")
logger.info(f"Site title: {settings.lnbits_site_title}")
logger.info(f"Funding source: {settings.lnbits_backend_wallet_class}")
logger.info(f"Data folder: {settings.lnbits_data_folder}")
logger.info(f"Database: {get_db_vendor_name()}")
logger.info(f"Service fee: {settings.lnbits_service_fee}")
logger.info(f"Service fee max: {settings.lnbits_service_fee_max}")
logger.info(f"Service fee wallet: {settings.lnbits_service_fee_wallet}")
def get_db_vendor_name():
db_url = settings.lnbits_database_url
return (
"PostgreSQL"
if db_url and db_url.startswith("postgres://")
else (
"CockroachDB"
if db_url and db_url.startswith("cockroachdb://")
else "SQLite"
)
)
def register_async_tasks(): def register_async_tasks():
@@ -468,148 +420,7 @@ def register_async_tasks():
# create_permanent_task(watchdog_task) # create_permanent_task(watchdog_task)
create_permanent_task(killswitch_task) create_permanent_task(killswitch_task)
# server logs for websocket
def register_exception_handlers(app: FastAPI): if settings.lnbits_admin_ui:
@app.exception_handler(Exception) server_log_task = initialize_server_websocket_logger()
async def exception_handler(request: Request, exc: Exception): create_permanent_task(server_log_task)
etype, _, tb = sys.exc_info()
traceback.print_exception(etype, exc, tb)
logger.error(f"Exception: {str(exc)}")
# Only the browser sends "text/html" request
# not fail proof, but everything else get's a JSON response
if (
request.headers
and "accept" in request.headers
and "text/html" in request.headers["accept"]
):
return template_renderer().TemplateResponse(
request, "error.html", {"err": f"Error: {str(exc)}"}
)
return JSONResponse(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
content={"detail": str(exc)},
)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(
request: Request, exc: RequestValidationError
):
logger.error(f"RequestValidationError: {str(exc)}")
# Only the browser sends "text/html" request
# not fail proof, but everything else get's a JSON response
if (
request.headers
and "accept" in request.headers
and "text/html" in request.headers["accept"]
):
return template_renderer().TemplateResponse(
request,
"error.html",
{"err": f"Error: {str(exc)}"},
)
return JSONResponse(
status_code=HTTPStatus.BAD_REQUEST,
content={"detail": str(exc)},
)
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
logger.error(f"HTTPException {exc.status_code}: {exc.detail}")
# Only the browser sends "text/html" request
# not fail proof, but everything else get's a JSON response
if (
request.headers
and "accept" in request.headers
and "text/html" in request.headers["accept"]
):
if exc.headers and "token-expired" in exc.headers:
response = RedirectResponse("/")
response.delete_cookie("cookie_access_token")
response.delete_cookie("is_lnbits_user_authorized")
response.set_cookie("is_access_token_expired", "true")
return response
return template_renderer().TemplateResponse(
request,
"error.html",
{
"request": request,
"err": f"HTTP Error {exc.status_code}: {exc.detail}",
},
)
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail},
)
def configure_logger() -> None:
logger.remove()
log_level: str = "DEBUG" if settings.debug else "INFO"
formatter = Formatter()
logger.add(sys.stdout, level=log_level, format=formatter.format)
if settings.enable_log_to_file:
logger.add(
Path(settings.lnbits_data_folder, "logs", "lnbits.log"),
rotation=settings.log_rotation,
retention=settings.log_retention,
level="INFO",
format=formatter.format,
)
logger.add(
Path(settings.lnbits_data_folder, "logs", "debug.log"),
rotation=settings.log_rotation,
retention=settings.log_retention,
level="DEBUG",
format=formatter.format,
)
logging.getLogger("uvicorn").handlers = [InterceptHandler()]
logging.getLogger("uvicorn.access").handlers = [InterceptHandler()]
logging.getLogger("uvicorn.error").handlers = [InterceptHandler()]
logging.getLogger("uvicorn.error").propagate = False
logging.getLogger("sqlalchemy").handlers = [InterceptHandler()]
logging.getLogger("sqlalchemy.engine.base").handlers = [InterceptHandler()]
logging.getLogger("sqlalchemy.engine.base").propagate = False
logging.getLogger("sqlalchemy.engine.base.Engine").handlers = [InterceptHandler()]
logging.getLogger("sqlalchemy.engine.base.Engine").propagate = False
class Formatter:
def __init__(self):
self.padding = 0
self.minimal_fmt = (
"<green>{time:YYYY-MM-DD HH:mm:ss.SS}</green> | <level>{level}</level> | "
"<level>{message}</level>\n"
)
if settings.debug:
self.fmt = (
"<green>{time:YYYY-MM-DD HH:mm:ss.SS}</green> | "
"<level>{level: <4}</level> | "
"<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
"<level>{message}</level>\n"
)
else:
self.fmt = self.minimal_fmt
def format(self, record):
function = "{function}".format(**record)
if function == "emit": # uvicorn logs
return self.minimal_fmt
return self.fmt
class InterceptHandler(logging.Handler):
def emit(self, record):
try:
level = logger.level(record.levelname).name
except ValueError:
level = record.levelno
logger.log(level, record.getMessage())
+8 -7
View File
@@ -83,7 +83,7 @@ def get_super_user() -> Optional[str]:
"Superuser id not found. Please check that the file " "Superuser id not found. Please check that the file "
+ f"'{superuser_file.absolute()}' exists and has read permissions." + f"'{superuser_file.absolute()}' exists and has read permissions."
) )
with open(superuser_file, "r") as file: with open(superuser_file) as file:
return file.readline() return file.readline()
@@ -124,7 +124,8 @@ def database_migrate():
async def db_migrate(): async def db_migrate():
asyncio.create_task(migrate_databases()) task = asyncio.create_task(migrate_databases())
await task
async def migrate_databases(): async def migrate_databases():
@@ -205,7 +206,7 @@ async def database_delete_wallet(wallet: str):
@click.option("-c", "--checking-id", required=True, help="Payment checking Id.") @click.option("-c", "--checking-id", required=True, help="Payment checking Id.")
@coro @coro
async def database_delete_wallet_payment(wallet: str, checking_id: str): async def database_delete_wallet_payment(wallet: str, checking_id: str):
"""Mark wallet as deleted""" """Delete wallet payment"""
async with core_db.connect() as conn: async with core_db.connect() as conn:
await delete_wallet_payment( await delete_wallet_payment(
wallet_id=wallet, checking_id=checking_id, conn=conn wallet_id=wallet, checking_id=checking_id, conn=conn
@@ -492,7 +493,7 @@ async def extensions_uninstall(
click.echo(f"Failed to uninstall '{extension}' Error: '{ex.detail}'.") click.echo(f"Failed to uninstall '{extension}' Error: '{ex.detail}'.")
return False, ex.detail return False, ex.detail
except Exception as ex: except Exception as ex:
click.echo(f"Failed to uninstall '{extension}': {str(ex)}.") click.echo(f"Failed to uninstall '{extension}': {ex!s}.")
return False, str(ex) return False, str(ex)
@@ -530,7 +531,7 @@ async def install_extension(
click.echo(f"Failed to install '{extension}' Error: '{ex.detail}'.") click.echo(f"Failed to install '{extension}' Error: '{ex.detail}'.")
return False, ex.detail return False, ex.detail
except Exception as ex: except Exception as ex:
click.echo(f"Failed to install '{extension}': {str(ex)}.") click.echo(f"Failed to install '{extension}': {ex!s}.")
return False, str(ex) return False, str(ex)
@@ -582,7 +583,7 @@ async def update_extension(
click.echo(f"Failed to update '{extension}' Error: '{ex.detail}.") click.echo(f"Failed to update '{extension}' Error: '{ex.detail}.")
return False, ex.detail return False, ex.detail
except Exception as ex: except Exception as ex:
click.echo(f"Failed to update '{extension}': {str(ex)}.") click.echo(f"Failed to update '{extension}': {ex!s}.")
return False, str(ex) return False, str(ex)
@@ -605,7 +606,7 @@ async def _select_release(
return latest_repo_releases[source_repo] return latest_repo_releases[source_repo]
if len(latest_repo_releases) == 1: if len(latest_repo_releases) == 1:
return latest_repo_releases[list(latest_repo_releases.keys())[0]] return latest_repo_releases[next(iter(latest_repo_releases.keys()))]
repos = list(latest_repo_releases.keys()) repos = list(latest_repo_releases.keys())
repos.sort() repos.sort()
+2
View File
@@ -12,6 +12,7 @@ from .views.node_api import node_router, public_node_router, super_node_router
from .views.payment_api import payment_router from .views.payment_api import payment_router
from .views.public_api import public_router from .views.public_api import public_router
from .views.tinyurl_api import tinyurl_router from .views.tinyurl_api import tinyurl_router
from .views.user_api import users_router
from .views.wallet_api import wallet_router from .views.wallet_api import wallet_router
from .views.webpush_api import webpush_router from .views.webpush_api import webpush_router
from .views.websocket_api import websocket_router from .views.websocket_api import websocket_router
@@ -36,3 +37,4 @@ def init_core_routers(app: FastAPI):
app.include_router(websocket_router) app.include_router(websocket_router)
app.include_router(tinyurl_router) app.include_router(tinyurl_router)
app.include_router(webpush_router) app.include_router(webpush_router)
app.include_router(users_router)
+88 -86
View File
@@ -2,14 +2,12 @@ import datetime
import json import json
from time import time from time import time
from typing import Any, Dict, List, Literal, Optional from typing import Any, Dict, List, Literal, Optional
from urllib.parse import urlparse
from uuid import UUID, uuid4 from uuid import UUID, uuid4
import shortuuid import shortuuid
from passlib.context import CryptContext from passlib.context import CryptContext
from lnbits.core.db import db from lnbits.core.db import db
from lnbits.core.models import WalletType
from lnbits.db import DB_TYPE, SQLITE, Connection, Database, Filters, Page from lnbits.db import DB_TYPE, SQLITE, Connection, Database, Filters, Page
from lnbits.extension_manager import InstallableExtension from lnbits.extension_manager import InstallableExtension
from lnbits.settings import ( from lnbits.settings import (
@@ -21,7 +19,8 @@ from lnbits.settings import (
) )
from .models import ( from .models import (
BalanceCheck, Account,
AccountFilters,
CreateUser, CreateUser,
Payment, Payment,
PaymentFilters, PaymentFilters,
@@ -147,6 +146,46 @@ async def update_account(
return user return user
async def delete_account(user_id: str, conn: Optional[Connection] = None) -> None:
await (conn or db).execute(
"DELETE from accounts WHERE id = ?",
(user_id,),
)
async def get_accounts(
filters: Optional[Filters[AccountFilters]] = None,
conn: Optional[Connection] = None,
) -> Page[Account]:
return await (conn or db).fetch_page(
"""
SELECT
accounts.id,
accounts.username,
accounts.email,
SUM(COALESCE((
SELECT balance FROM balances WHERE wallet = wallets.id
), 0)) as balance_msat,
SUM((
SELECT COUNT(*) FROM apipayments WHERE wallet = wallets.id
)) as transaction_count,
(
SELECT COUNT(*) FROM wallets WHERE wallets.user = accounts.id
) as wallet_count,
MAX((
SELECT time FROM apipayments
WHERE wallet = wallets.id ORDER BY time DESC LIMIT 1
)) as last_payment
FROM accounts LEFT JOIN wallets ON accounts.id = wallets.user
""",
[],
[],
filters=filters,
model=Account,
group_by=["accounts.id"],
)
async def get_account( async def get_account(
user_id: str, conn: Optional[Connection] = None user_id: str, conn: Optional[Connection] = None
) -> Optional[User]: ) -> Optional[User]:
@@ -168,14 +207,21 @@ async def delete_accounts_no_wallets(
time_delta: int, time_delta: int,
conn: Optional[Connection] = None, conn: Optional[Connection] = None,
) -> None: ) -> None:
delta = int(time()) - time_delta
await (conn or db).execute( await (conn or db).execute(
f""" f"""
DELETE FROM accounts DELETE FROM accounts
WHERE NOT EXISTS ( WHERE NOT EXISTS (
SELECT wallets.id FROM wallets WHERE wallets.user = accounts.id SELECT wallets.id FROM wallets WHERE wallets.user = accounts.id
) AND updated_at < {db.timestamp_placeholder} ) AND (
(updated_at is null AND created_at < {db.timestamp_placeholder})
OR updated_at < {db.timestamp_placeholder}
)
""", """,
(int(time()) - time_delta,), (
delta,
delta,
),
) )
@@ -500,16 +546,29 @@ async def update_wallet(
async def delete_wallet( async def delete_wallet(
*, user_id: str, wallet_id: str, conn: Optional[Connection] = None *,
user_id: str,
wallet_id: str,
deleted: bool = True,
conn: Optional[Connection] = None,
) -> None: ) -> None:
now = int(time()) now = int(time())
await (conn or db).execute( await (conn or db).execute(
f""" f"""
UPDATE wallets UPDATE wallets
SET deleted = true, updated_at = {db.timestamp_placeholder} SET deleted = ?, updated_at = {db.timestamp_placeholder}
WHERE id = ? AND "user" = ? WHERE id = ? AND "user" = ?
""", """,
(now, wallet_id, user_id), (deleted, now, wallet_id, user_id),
)
async def force_delete_wallet(
wallet_id: str, conn: Optional[Connection] = None
) -> None:
await (conn or db).execute(
"DELETE FROM wallets WHERE id = ?",
(wallet_id,),
) )
@@ -536,14 +595,21 @@ async def delete_unused_wallets(
time_delta: int, time_delta: int,
conn: Optional[Connection] = None, conn: Optional[Connection] = None,
) -> None: ) -> None:
delta = int(time()) - time_delta
await (conn or db).execute( await (conn or db).execute(
f""" f"""
DELETE FROM wallets DELETE FROM wallets
WHERE ( WHERE (
SELECT COUNT(*) FROM apipayments WHERE wallet = wallets.id SELECT COUNT(*) FROM apipayments WHERE wallet = wallets.id
) = 0 AND updated_at < {db.timestamp_placeholder} ) = 0 AND (
(updated_at is null AND created_at < {db.timestamp_placeholder})
OR updated_at < {db.timestamp_placeholder}
)
""", """,
(int(time()) - time_delta,), (
delta,
delta,
),
) )
@@ -561,9 +627,20 @@ async def get_wallet(
return Wallet(**row) if row else None return Wallet(**row) if row else None
async def get_wallets(user_id: str, conn: Optional[Connection] = None) -> List[Wallet]:
rows = await (conn or db).fetchall(
"""
SELECT *, COALESCE((SELECT balance FROM balances WHERE wallet = wallets.id), 0)
AS balance_msat FROM wallets WHERE "user" = ?
""",
(user_id,),
)
return [Wallet(**row) for row in rows]
async def get_wallet_for_key( async def get_wallet_for_key(
key: str, key: str,
key_type: WalletType = WalletType.invoice,
conn: Optional[Connection] = None, conn: Optional[Connection] = None,
) -> Optional[Wallet]: ) -> Optional[Wallet]:
row = await (conn or db).fetchone( row = await (conn or db).fetchone(
@@ -578,9 +655,6 @@ async def get_wallet_for_key(
if not row: if not row:
return None return None
if key_type == WalletType.admin and row["adminkey"] != key:
return None
return Wallet(**row) return Wallet(**row)
@@ -589,11 +663,6 @@ async def get_total_balance(conn: Optional[Connection] = None):
return 0 if row[0] is None else row[0] return 0 if row[0] is None else row[0]
async def get_active_wallet_total_balance(conn: Optional[Connection] = None):
row = await (conn or db).fetchone("SELECT SUM(balance) FROM balances")
return 0 if row[0] is None else row[0]
# wallet payments # wallet payments
# --------------- # ---------------
@@ -1040,73 +1109,6 @@ async def mark_webhook_sent(payment_hash: str, status: int) -> None:
) )
# balance_check
# -------------
async def save_balance_check(
wallet_id: str, url: str, conn: Optional[Connection] = None
):
domain = urlparse(url).netloc
await (conn or db).execute(
"""
INSERT INTO balance_check (wallet, service, url) VALUES (?, ?, ?)
ON CONFLICT (wallet, service) DO UPDATE SET url = ?
""",
(wallet_id, domain, url, url),
)
async def get_balance_check(
wallet_id: str, domain: str, conn: Optional[Connection] = None
) -> Optional[BalanceCheck]:
row = await (conn or db).fetchone(
"""
SELECT wallet, service, url
FROM balance_check
WHERE wallet = ? AND service = ?
""",
(wallet_id, domain),
)
return BalanceCheck.from_row(row) if row else None
async def get_balance_checks(conn: Optional[Connection] = None) -> List[BalanceCheck]:
rows = await (conn or db).fetchall("SELECT wallet, service, url FROM balance_check")
return [BalanceCheck.from_row(row) for row in rows]
# balance_notify
# --------------
async def save_balance_notify(
wallet_id: str, url: str, conn: Optional[Connection] = None
):
await (conn or db).execute(
"""
INSERT INTO balance_notify (wallet, url) VALUES (?, ?)
ON CONFLICT (wallet) DO UPDATE SET url = ?
""",
(wallet_id, url, url),
)
async def get_balance_notify(
wallet_id: str, conn: Optional[Connection] = None
) -> Optional[str]:
row = await (conn or db).fetchone(
"""
SELECT url
FROM balance_notify
WHERE wallet = ?
""",
(wallet_id,),
)
return row[0] if row else None
# admin # admin
# -------- # --------
+5 -5
View File
@@ -18,11 +18,11 @@ async def migrate_extension_database(ext: Extension, current_version):
try: try:
ext_migrations = importlib.import_module(f"{ext.module_name}.migrations") ext_migrations = importlib.import_module(f"{ext.module_name}.migrations")
ext_db = importlib.import_module(ext.module_name).db ext_db = importlib.import_module(ext.module_name).db
except ImportError as e: except ImportError as exc:
logger.error(e) logger.error(exc)
raise ImportError( raise ImportError(
f"Please make sure that the extension `{ext.code}` has a migrations file." f"Please make sure that the extension `{ext.code}` has a migrations file."
) ) from exc
async with ext_db.connect() as ext_conn: async with ext_db.connect() as ext_conn:
await run_migration(ext_conn, ext_migrations, ext.code, current_version) await run_migration(ext_conn, ext_migrations, ext.code, current_version)
@@ -113,7 +113,7 @@ def to_valid_user_id(user_id: str) -> UUID:
raise ValueError("User ID must have at least 128 bits") raise ValueError("User ID must have at least 128 bits")
try: try:
int(user_id, 16) int(user_id, 16)
except Exception: except Exception as exc:
raise ValueError("Invalid hex string for User ID.") raise ValueError("Invalid hex string for User ID.") from exc
return UUID(hex=user_id[:32], version=4) return UUID(hex=user_id[:32], version=4)
+41
View File
@@ -471,3 +471,44 @@ async def m017_add_timestamp_columns_to_accounts_and_wallets(db):
except OperationalError as exc: except OperationalError as exc:
logger.error(f"Migration 17 failed: {exc}") logger.error(f"Migration 17 failed: {exc}")
pass pass
async def m018_balances_view_exclude_deleted(db):
"""
Make deleted wallets not show up in the balances view.
"""
await db.execute("DROP VIEW balances")
await db.execute(
"""
CREATE VIEW balances AS
SELECT apipayments.wallet,
SUM(apipayments.amount - ABS(apipayments.fee)) AS balance
FROM apipayments
LEFT JOIN wallets ON apipayments.wallet = wallets.id
WHERE (wallets.deleted = false OR wallets.deleted is NULL)
AND ((apipayments.pending = false AND apipayments.amount > 0)
OR apipayments.amount < 0)
GROUP BY wallet
"""
)
async def m019_balances_view_based_on_wallets(db):
"""
Make deleted wallets not show up in the balances view.
Important for querying whole lnbits balances.
"""
await db.execute("DROP VIEW balances")
await db.execute(
"""
CREATE VIEW balances AS
SELECT apipayments.wallet,
SUM(apipayments.amount - ABS(apipayments.fee)) AS balance
FROM wallets
LEFT JOIN apipayments ON apipayments.wallet = wallets.id
WHERE (wallets.deleted = false OR wallets.deleted is NULL)
AND ((apipayments.pending = false AND apipayments.amount > 0)
OR apipayments.amount < 0)
GROUP BY apipayments.wallet
"""
)
+47 -18
View File
@@ -17,7 +17,7 @@ from lnbits.db import Connection, FilterModel, FromRowModel
from lnbits.helpers import url_for from lnbits.helpers import url_for
from lnbits.lnurl import encode as lnurl_encode from lnbits.lnurl import encode as lnurl_encode
from lnbits.settings import settings from lnbits.settings import settings
from lnbits.wallets import get_wallet_class from lnbits.wallets import get_funding_source
from lnbits.wallets.base import PaymentPendingStatus, PaymentStatus from lnbits.wallets.base import PaymentPendingStatus, PaymentStatus
@@ -68,7 +68,7 @@ class Wallet(BaseWallet):
return await get_standalone_payment(payment_hash) return await get_standalone_payment(payment_hash)
class WalletType(Enum): class KeyType(Enum):
admin = 0 admin = 0
invoice = 1 invoice = 1
invalid = 2 invalid = 2
@@ -80,7 +80,7 @@ class WalletType(Enum):
@dataclass @dataclass
class WalletTypeInfo: class WalletTypeInfo:
wallet_type: WalletType key_type: KeyType
wallet: Wallet wallet: Wallet
@@ -97,6 +97,37 @@ class UserConfig(BaseModel):
provider: Optional[str] = "lnbits" # auth provider provider: Optional[str] = "lnbits" # auth provider
class Account(FromRowModel):
id: str
is_super_user: Optional[bool] = False
is_admin: Optional[bool] = False
username: Optional[str] = None
email: Optional[str] = None
balance_msat: Optional[int] = 0
transaction_count: Optional[int] = 0
wallet_count: Optional[int] = 0
last_payment: Optional[datetime.datetime] = None
class AccountFilters(FilterModel):
__search_fields__ = ["id", "email", "username"]
__sort_fields__ = [
"balance_msat",
"email",
"username",
"transaction_count",
"wallet_count",
"last_payment",
]
id: str
last_payment: Optional[datetime.datetime] = None
transaction_count: Optional[int] = None
wallet_count: Optional[int] = None
username: Optional[str] = None
email: Optional[str] = None
class User(BaseModel): class User(BaseModel):
id: str id: str
email: Optional[str] = None email: Optional[str] = None
@@ -265,11 +296,11 @@ class Payment(FromRowModel):
f"pending payment {self.checking_id}" f"pending payment {self.checking_id}"
) )
WALLET = get_wallet_class() funding_source = get_funding_source()
if self.is_out: if self.is_out:
status = await WALLET.get_payment_status(self.checking_id) status = await funding_source.get_payment_status(self.checking_id)
else: else:
status = await WALLET.get_invoice_status(self.checking_id) status = await funding_source.get_invoice_status(self.checking_id)
logger.debug(f"Status: {status}") logger.debug(f"Status: {status}")
@@ -331,16 +362,6 @@ class PaymentHistoryPoint(BaseModel):
balance: int balance: int
class BalanceCheck(BaseModel):
wallet: str
service: str
url: str
@classmethod
def from_row(cls, row: Row):
return cls(wallet=row["wallet"], service=row["service"], url=row["url"])
def _do_nothing(*_): def _do_nothing(*_):
pass pass
@@ -394,11 +415,10 @@ class CreateInvoice(BaseModel):
description_hash: Optional[str] = None description_hash: Optional[str] = None
unhashed_description: Optional[str] = None unhashed_description: Optional[str] = None
expiry: Optional[int] = None expiry: Optional[int] = None
lnurl_callback: Optional[str] = None
lnurl_balance_check: Optional[str] = None
extra: Optional[dict] = None extra: Optional[dict] = None
webhook: Optional[str] = None webhook: Optional[str] = None
bolt11: Optional[str] = None bolt11: Optional[str] = None
lnurl_callback: Optional[str] = None
class CreateTopup(BaseModel): class CreateTopup(BaseModel):
@@ -424,3 +444,12 @@ class WebPushSubscription(BaseModel):
data: str data: str
host: str host: str
timestamp: str timestamp: str
class BalanceDelta(BaseModel):
lnbits_balance_msats: int
node_balance_msats: int
@property
def delta_msats(self):
return self.node_balance_msats - self.lnbits_balance_msats
+67 -60
View File
@@ -8,7 +8,6 @@ from typing import Dict, List, Optional, Tuple, TypedDict
from urllib.parse import parse_qs, urlparse from urllib.parse import parse_qs, urlparse
import httpx import httpx
from bolt11 import Bolt11
from bolt11 import decode as bolt11_decode from bolt11 import decode as bolt11_decode
from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives import serialization
from fastapi import Depends, WebSocket from fastapi import Depends, WebSocket
@@ -30,7 +29,7 @@ from lnbits.settings import (
settings, settings,
) )
from lnbits.utils.exchange_rates import fiat_amount_as_satoshis, satoshis_amount_as_fiat from lnbits.utils.exchange_rates import fiat_amount_as_satoshis, satoshis_amount_as_fiat
from lnbits.wallets import FAKE_WALLET, get_wallet_class, set_wallet_class from lnbits.wallets import fake_wallet, get_funding_source, set_funding_source
from lnbits.wallets.base import ( from lnbits.wallets.base import (
PaymentPendingStatus, PaymentPendingStatus,
PaymentResponse, PaymentResponse,
@@ -59,15 +58,19 @@ from .crud import (
update_super_user, update_super_user,
) )
from .helpers import to_valid_user_id from .helpers import to_valid_user_id
from .models import Payment, UserConfig, Wallet from .models import BalanceDelta, Payment, UserConfig, Wallet
class PaymentFailure(Exception): class PaymentError(Exception):
pass def __init__(self, message: str, status: str = "pending"):
self.message = message
self.status = status
class InvoiceFailure(Exception): class InvoiceError(Exception):
pass def __init__(self, message: str, status: str = "pending"):
self.message = message
self.status = status
async def calculate_fiat_amounts( async def calculate_fiat_amounts(
@@ -123,16 +126,16 @@ async def create_invoice(
conn: Optional[Connection] = None, conn: Optional[Connection] = None,
) -> Tuple[str, str]: ) -> Tuple[str, str]:
if not amount > 0: if not amount > 0:
raise InvoiceFailure("Amountless invoices not supported.") raise InvoiceError("Amountless invoices not supported.", status="failed")
user_wallet = await get_wallet(wallet_id, conn=conn) user_wallet = await get_wallet(wallet_id, conn=conn)
if not user_wallet: if not user_wallet:
raise InvoiceFailure(f"Could not fetch wallet '{wallet_id}'.") raise InvoiceError(f"Could not fetch wallet '{wallet_id}'.", status="failed")
invoice_memo = None if description_hash else memo invoice_memo = None if description_hash else memo
# use the fake wallet if the invoice is for internal use only # use the fake wallet if the invoice is for internal use only
wallet = FAKE_WALLET if internal else get_wallet_class() funding_source = fake_wallet if internal else get_funding_source()
amount_sat, extra = await calculate_fiat_amounts( amount_sat, extra = await calculate_fiat_amounts(
amount, wallet_id, currency=currency, extra=extra, conn=conn amount, wallet_id, currency=currency, extra=extra, conn=conn
@@ -141,12 +144,18 @@ async def create_invoice(
if settings.is_wallet_max_balance_exceeded( if settings.is_wallet_max_balance_exceeded(
user_wallet.balance_msat / 1000 + amount_sat user_wallet.balance_msat / 1000 + amount_sat
): ):
raise InvoiceFailure( raise InvoiceError(
f"Wallet balance cannot exceed " f"Wallet balance cannot exceed "
f"{settings.lnbits_wallet_limit_max_balance} sats." f"{settings.lnbits_wallet_limit_max_balance} sats.",
status="failed",
) )
ok, checking_id, payment_request, error_message = await wallet.create_invoice( (
ok,
checking_id,
payment_request,
error_message,
) = await funding_source.create_invoice(
amount=amount_sat, amount=amount_sat,
memo=invoice_memo, memo=invoice_memo,
description_hash=description_hash, description_hash=description_hash,
@@ -154,7 +163,9 @@ async def create_invoice(
expiry=expiry or settings.lightning_invoice_expiry, expiry=expiry or settings.lightning_invoice_expiry,
) )
if not ok or not payment_request or not checking_id: if not ok or not payment_request or not checking_id:
raise InvoiceFailure(error_message or "unexpected backend error.") raise InvoiceError(
error_message or "unexpected backend error.", status="pending"
)
invoice = bolt11_decode(payment_request) invoice = bolt11_decode(payment_request)
@@ -165,7 +176,7 @@ async def create_invoice(
payment_request=payment_request, payment_request=payment_request,
payment_hash=invoice.payment_hash, payment_hash=invoice.payment_hash,
amount=amount_msat, amount=amount_msat,
expiry=get_bolt11_expiry(invoice), expiry=invoice.expiry_date,
memo=memo, memo=memo,
extra=extra, extra=extra,
webhook=webhook, webhook=webhook,
@@ -196,13 +207,13 @@ async def pay_invoice(
""" """
try: try:
invoice = bolt11_decode(payment_request) invoice = bolt11_decode(payment_request)
except Exception: except Exception as exc:
raise InvoiceFailure("Bolt11 decoding failed.") raise PaymentError("Bolt11 decoding failed.", status="failed") from exc
if not invoice.amount_msat or not invoice.amount_msat > 0: if not invoice.amount_msat or not invoice.amount_msat > 0:
raise InvoiceFailure("Amountless invoices not supported.") raise PaymentError("Amountless invoices not supported.", status="failed")
if max_sat and invoice.amount_msat > max_sat * 1000: if max_sat and invoice.amount_msat > max_sat * 1000:
raise InvoiceFailure("Amount in invoice is too high.") raise PaymentError("Amount in invoice is too high.", status="failed")
await check_wallet_limits(wallet_id, conn, invoice.amount_msat) await check_wallet_limits(wallet_id, conn, invoice.amount_msat)
@@ -229,7 +240,7 @@ async def pay_invoice(
payment_request=payment_request, payment_request=payment_request,
payment_hash=invoice.payment_hash, payment_hash=invoice.payment_hash,
amount=-invoice.amount_msat, amount=-invoice.amount_msat,
expiry=get_bolt11_expiry(invoice), expiry=invoice.expiry_date,
memo=description or invoice.description or "", memo=description or invoice.description or "",
extra=extra, extra=extra,
) )
@@ -237,7 +248,7 @@ async def pay_invoice(
# we check if an internal invoice exists that has already been paid # we check if an internal invoice exists that has already been paid
# (not pending anymore) # (not pending anymore)
if not await check_internal_pending(invoice.payment_hash, conn=conn): if not await check_internal_pending(invoice.payment_hash, conn=conn):
raise PaymentFailure("Internal invoice already paid.") raise PaymentError("Internal invoice already paid.", status="failed")
# check_internal() returns the checking_id of the invoice we're waiting for # check_internal() returns the checking_id of the invoice we're waiting for
# (pending only) # (pending only)
@@ -256,7 +267,7 @@ async def pay_invoice(
internal_invoice.amount != invoice.amount_msat internal_invoice.amount != invoice.amount_msat
or internal_invoice.bolt11 != payment_request.lower() or internal_invoice.bolt11 != payment_request.lower()
): ):
raise PaymentFailure("Invalid invoice.") raise PaymentError("Invalid invoice.", status="failed")
logger.debug(f"creating temporary internal payment with id {internal_id}") logger.debug(f"creating temporary internal payment with id {internal_id}")
# create a new payment from this wallet # create a new payment from this wallet
@@ -281,10 +292,10 @@ async def pay_invoice(
conn=conn, conn=conn,
**payment_kwargs, **payment_kwargs,
) )
except Exception as e: except Exception as exc:
logger.error(f"could not create temporary payment: {e}") logger.error(f"could not create temporary payment: {exc}")
# happens if the same wallet tries to pay an invoice twice # happens if the same wallet tries to pay an invoice twice
raise PaymentFailure("Could not make payment.") raise PaymentError("Could not make payment.", status="failed") from exc
# do the balance check # do the balance check
wallet = await get_wallet(wallet_id, conn=conn) wallet = await get_wallet(wallet_id, conn=conn)
@@ -295,11 +306,12 @@ async def pay_invoice(
not internal_checking_id not internal_checking_id
and wallet.balance_msat > -fee_reserve_total_msat and wallet.balance_msat > -fee_reserve_total_msat
): ):
raise PaymentFailure( raise PaymentError(
f"You must reserve at least ({round(fee_reserve_total_msat/1000)}" f"You must reserve at least ({round(fee_reserve_total_msat/1000)}"
" sat) to cover potential routing fees." " sat) to cover potential routing fees.",
status="failed",
) )
raise PermissionError("Insufficient balance.") raise PaymentError("Insufficient balance.", status="failed")
if internal_checking_id: if internal_checking_id:
service_fee_msat = service_fee(invoice.amount_msat, internal=True) service_fee_msat = service_fee(invoice.amount_msat, internal=True)
@@ -323,8 +335,8 @@ async def pay_invoice(
service_fee_msat = service_fee(invoice.amount_msat, internal=False) service_fee_msat = service_fee(invoice.amount_msat, internal=False)
logger.debug(f"backend: sending payment {temp_id}") logger.debug(f"backend: sending payment {temp_id}")
# actually pay the external invoice # actually pay the external invoice
WALLET = get_wallet_class() funding_source = get_funding_source()
payment: PaymentResponse = await WALLET.pay_invoice( payment: PaymentResponse = await funding_source.pay_invoice(
payment_request, fee_reserve_msat payment_request, fee_reserve_msat
) )
@@ -335,6 +347,7 @@ async def pay_invoice(
) )
logger.debug(f"backend: pay_invoice finished {temp_id}") logger.debug(f"backend: pay_invoice finished {temp_id}")
logger.debug(f"backend: pay_invoice response {payment}")
if payment.checking_id and payment.ok is not False: if payment.checking_id and payment.ok is not False:
# payment.ok can be True (paid) or None (pending)! # payment.ok can be True (paid) or None (pending)!
logger.debug(f"updating payment {temp_id}") logger.debug(f"updating payment {temp_id}")
@@ -363,9 +376,10 @@ async def pay_invoice(
async with db.connect() as conn: async with db.connect() as conn:
logger.debug(f"deleting temporary payment {temp_id}") logger.debug(f"deleting temporary payment {temp_id}")
await delete_wallet_payment(temp_id, wallet_id, conn=conn) await delete_wallet_payment(temp_id, wallet_id, conn=conn)
raise PaymentFailure( raise PaymentError(
f"Payment failed: {payment.error_message}" f"Payment failed: {payment.error_message}"
or "Payment failed, but backend didn't give us an error message." or "Payment failed, but backend didn't give us an error message.",
status="failed",
) )
else: else:
logger.warning( logger.warning(
@@ -408,8 +422,9 @@ async def check_time_limit_between_transactions(conn, wallet_id):
if len(payments) == 0: if len(payments) == 0:
return return
raise ValueError( raise PaymentError(
f"The time limit of {limit} seconds between payments has been reached." status="failed",
message=f"The time limit of {limit} seconds between payments has been reached.",
) )
@@ -499,7 +514,6 @@ async def redeem_lnurl_withdraw(
async def perform_lnurlauth( async def perform_lnurlauth(
callback: str, callback: str,
wallet: WalletTypeInfo = Depends(require_admin_key), wallet: WalletTypeInfo = Depends(require_admin_key),
conn: Optional[Connection] = None,
) -> Optional[LnurlErrorResponse]: ) -> Optional[LnurlErrorResponse]:
cb = urlparse(callback) cb = urlparse(callback)
@@ -592,7 +606,7 @@ async def check_transaction_status(
# WARN: this same value must be used for balance check and passed to # WARN: this same value must be used for balance check and passed to
# WALLET.pay_invoice(), it may cause a vulnerability if the values differ # funding_source.pay_invoice(), it may cause a vulnerability if the values differ
def fee_reserve(amount_msat: int, internal: bool = False) -> int: def fee_reserve(amount_msat: int, internal: bool = False) -> int:
if internal: if internal:
return 0 return 0
@@ -621,7 +635,7 @@ def fee_reserve_total(amount_msat: int, internal: bool = False) -> int:
async def send_payment_notification(wallet: Wallet, payment: Payment): async def send_payment_notification(wallet: Wallet, payment: Payment):
await websocketUpdater( await websocket_updater(
wallet.id, wallet.id,
json.dumps( json.dumps(
{ {
@@ -723,7 +737,7 @@ def update_cached_settings(sets_dict: dict):
except Exception: except Exception:
logger.warning(f"Failed overriding setting: {key}, value: {value}") logger.warning(f"Failed overriding setting: {key}, value: {value}")
if "super_user" in sets_dict: if "super_user" in sets_dict:
setattr(settings, "super_user", sets_dict["super_user"]) settings.super_user = sets_dict["super_user"]
async def init_admin_settings(super_user: Optional[str] = None) -> SuperSettings: async def init_admin_settings(super_user: Optional[str] = None) -> SuperSettings:
@@ -760,33 +774,26 @@ class WebsocketConnectionManager:
await connection.send_text(message) await connection.send_text(message)
websocketManager = WebsocketConnectionManager() websocket_manager = WebsocketConnectionManager()
async def websocketUpdater(item_id, data): async def websocket_updater(item_id, data):
return await websocketManager.send_data(f"{data}", item_id) return await websocket_manager.send_data(f"{data}", item_id)
async def switch_to_voidwallet() -> None: async def switch_to_voidwallet() -> None:
WALLET = get_wallet_class() funding_source = get_funding_source()
if WALLET.__class__.__name__ == "VoidWallet": if funding_source.__class__.__name__ == "VoidWallet":
return return
set_wallet_class("VoidWallet") set_funding_source("VoidWallet")
settings.lnbits_backend_wallet_class = "VoidWallet" settings.lnbits_backend_wallet_class = "VoidWallet"
async def get_balance_delta() -> Tuple[int, int, int]: async def get_balance_delta() -> BalanceDelta:
WALLET = get_wallet_class() funding_source = get_funding_source()
total_balance = await get_total_balance() status = await funding_source.status()
error_message, node_balance = await WALLET.status() lnbits_balance = await get_total_balance()
if error_message: return BalanceDelta(
raise Exception(error_message) lnbits_balance_msats=lnbits_balance,
return node_balance - total_balance, node_balance, total_balance node_balance_msats=status.balance_msat,
)
def get_bolt11_expiry(invoice: Bolt11) -> datetime.datetime:
if invoice.expiry:
return datetime.datetime.fromtimestamp(invoice.date + invoice.expiry)
else:
# assume maximum bolt11 expiry of 31 days to be on the safe side
return datetime.datetime.now() + datetime.timedelta(days=31)
+17 -34
View File
@@ -5,7 +5,6 @@ import httpx
from loguru import logger from loguru import logger
from lnbits.core.crud import ( from lnbits.core.crud import (
get_balance_notify,
get_wallet, get_wallet,
get_webpush_subscriptions_for_user, get_webpush_subscriptions_for_user,
mark_webhook_sent, mark_webhook_sent,
@@ -16,7 +15,7 @@ from lnbits.core.services import (
send_payment_notification, send_payment_notification,
switch_to_voidwallet, switch_to_voidwallet,
) )
from lnbits.settings import get_wallet_class, settings from lnbits.settings import get_funding_source, settings
from lnbits.tasks import send_push_notification from lnbits.tasks import send_push_notification
api_invoice_listeners: Dict[str, asyncio.Queue] = {} api_invoice_listeners: Dict[str, asyncio.Queue] = {}
@@ -27,9 +26,12 @@ async def killswitch_task():
killswitch will check lnbits-status repository for a signal from killswitch will check lnbits-status repository for a signal from
LNbits and will switch to VoidWallet if the killswitch is triggered. LNbits and will switch to VoidWallet if the killswitch is triggered.
""" """
while True: while settings.lnbits_running:
WALLET = get_wallet_class() funding_source = get_funding_source()
if settings.lnbits_killswitch and WALLET.__class__.__name__ != "VoidWallet": if (
settings.lnbits_killswitch
and funding_source.__class__.__name__ != "VoidWallet"
):
with httpx.Client() as client: with httpx.Client() as client:
try: try:
r = client.get(settings.lnbits_status_manifest, timeout=4) r = client.get(settings.lnbits_status_manifest, timeout=4)
@@ -54,11 +56,15 @@ async def watchdog_task():
Registers a watchdog which will check lnbits balance and nodebalance Registers a watchdog which will check lnbits balance and nodebalance
and will switch to VoidWallet if the watchdog delta is reached. and will switch to VoidWallet if the watchdog delta is reached.
""" """
while True: while settings.lnbits_running:
WALLET = get_wallet_class() funding_source = get_funding_source()
if settings.lnbits_watchdog and WALLET.__class__.__name__ != "VoidWallet": if (
settings.lnbits_watchdog
and funding_source.__class__.__name__ != "VoidWallet"
):
try: try:
delta, *_ = await get_balance_delta() balance = await get_balance_delta()
delta = balance.delta_msats
logger.debug(f"Running watchdog task. current delta: {delta}") logger.debug(f"Running watchdog task. current delta: {delta}")
if delta + settings.lnbits_watchdog_delta <= 0: if delta + settings.lnbits_watchdog_delta <= 0:
logger.error(f"Switching to VoidWallet. current delta: {delta}") logger.error(f"Switching to VoidWallet. current delta: {delta}")
@@ -70,10 +76,9 @@ async def watchdog_task():
async def wait_for_paid_invoices(invoice_paid_queue: asyncio.Queue): async def wait_for_paid_invoices(invoice_paid_queue: asyncio.Queue):
""" """
This task dispatches events to all api_invoice_listeners, This worker dispatches events to all extensions and dispatches webhooks.
webhooks, push notifications and balance notifications.
""" """
while True: while settings.lnbits_running:
payment = await invoice_paid_queue.get() payment = await invoice_paid_queue.get()
logger.trace("received invoice paid event") logger.trace("received invoice paid event")
# dispatch api_invoice_listeners # dispatch api_invoice_listeners
@@ -85,28 +90,6 @@ async def wait_for_paid_invoices(invoice_paid_queue: asyncio.Queue):
# dispatch webhook # dispatch webhook
if payment.webhook and not payment.webhook_status: if payment.webhook and not payment.webhook_status:
await dispatch_webhook(payment) await dispatch_webhook(payment)
# dispatch balance_notify
url = await get_balance_notify(payment.wallet_id)
if url:
headers = {"User-Agent": settings.user_agent}
async with httpx.AsyncClient(headers=headers) as client:
try:
r = await client.post(url, timeout=4)
r.raise_for_status()
await mark_webhook_sent(payment.payment_hash, r.status_code)
except httpx.HTTPStatusError as exc:
status_code = exc.response.status_code
await mark_webhook_sent(payment.payment_hash, status_code)
logger.warning(
f"balance_notify returned a bad status_code: {status_code} "
f"while requesting {exc.request.url!r}."
)
logger.warning(exc)
except httpx.RequestError as exc:
await mark_webhook_sent(payment.payment_hash, -1)
logger.warning(f"Could not send balance_notify to {url}")
logger.warning(exc)
# dispatch push notification # dispatch push notification
await send_payment_push_notification(payment) await send_payment_push_notification(payment)
+35 -5
View File
@@ -4,7 +4,7 @@
<br /> <br />
<div> <div>
<div class="row q-col-gutter-md"> <div class="row q-col-gutter-md">
<div class="col-12 col-md-6"> <div class="col-12 col-md-5">
<p>Site Title</p> <p>Site Title</p>
<q-input <q-input
filled filled
@@ -14,7 +14,7 @@
></q-input> ></q-input>
<br /> <br />
</div> </div>
<div class="col-12 col-md-6"> <div class="col-12 col-md-5">
<p>Site Tagline</p> <p>Site Tagline</p>
<q-input <q-input
filled filled
@@ -24,7 +24,15 @@
></q-input> ></q-input>
<br /> <br />
</div> </div>
<div class="col-12 col-md-2 q-mt-xl">
<q-toggle
tip="Remove homepage elements like 'runs on' etc"
v-model="formData.LNBITS_SHOW_HOME_PAGE_ELEMENTS"
:label="formData.LNBITS_SHOW_HOME_PAGE_ELEMENTS ? 'Enable elements on homepage' : 'Disable elements on homepage'"
></q-toggle>
</div>
</div> </div>
<div> <div>
<p>Site Description</p> <p>Site Description</p>
<q-input <q-input
@@ -44,7 +52,6 @@
v-model="formData.lnbits_default_wallet_name" v-model="formData.lnbits_default_wallet_name"
label="LNbits wallet" label="LNbits wallet"
></q-input> ></q-input>
<br />
</div> </div>
<div class="col-12 col-md-4"> <div class="col-12 col-md-4">
<p>Denomination</p> <p>Denomination</p>
@@ -55,7 +62,6 @@
label="sats" label="sats"
hint="The name for the FakeWallet token" hint="The name for the FakeWallet token"
></q-input> ></q-input>
<br />
</div> </div>
<div class="col-12 col-md-4"> <div class="col-12 col-md-4">
<p>QR code logo</p> <p>QR code logo</p>
@@ -66,9 +72,33 @@
label="https://example.com/image.svg" label="https://example.com/image.svg"
hint="URL to logo image in QR code" hint="URL to logo image in QR code"
></q-input> ></q-input>
<br />
</div> </div>
</div> </div>
<div class="row q-col-gutter-md">
<div class="col-12 col-md-4">
<p>Custom Badge</p>
<div class="row q-col-gutter-md">
<div class="col-12 col-md-8">
<q-input
filled
type="text"
tip="Custom Badge"
v-model="formData.lnbits_custom_badge"
label="Custom Badge 'USE WITH CAUTION - LNbits wallet is still in BETA'"
></q-input>
</div>
<div class="col-12 col-md-4">
<q-select
filled
v-model="formData.lnbits_custom_badge_color"
:options="colors"
label="Custom badge color"
></q-select>
</div>
</div>
</div>
</div>
<br />
<div class="row q-col-gutter-md"> <div class="row q-col-gutter-md">
<div class="col-12 col-md-6"> <div class="col-12 col-md-6">
<p>Themes</p> <p>Themes</p>
-59
View File
@@ -40,17 +40,6 @@
/> />
</q-btn> </q-btn>
<q-btn
v-if="isSuperUser"
:label="$t('topup')"
color="primary"
@click="topUpDialog.show = true"
>
<q-tooltip>
<span v-text="$t('add_funds_tooltip')"></span>
</q-tooltip>
</q-btn>
<q-btn :label="$t('download_backup')" flat @click="downloadBackup"></q-btn> <q-btn :label="$t('download_backup')" flat @click="downloadBackup"></q-btn>
<q-btn <q-btn
@@ -119,54 +108,6 @@
</div> </div>
</div> </div>
<q-dialog v-if="isSuperUser" v-model="topUpDialog.show" position="top">
<q-card class="q-pa-lg q-pt-xl lnbits__dialog-card">
<q-form class="q-gutter-md">
<p v-text="$t('topup_wallet')"></p>
<div class="row">
<div class="col-12">
<q-input
dense
type="text"
filled
v-model="wallet.id"
label="Wallet ID"
:hint="$t('topup_hint')"
></q-input>
<br />
</div>
<div class="col-12">
<q-input
dense
type="number"
filled
v-model="wallet.amount"
:label="$t('amount')"
></q-input>
</div>
</div>
<div class="row q-mt-lg">
<q-btn
:label="$t('topup')"
color="primary"
@click="topupWallet"
></q-btn>
<q-btn
v-close-popup
flat
color="grey"
class="q-ml-auto"
:label="$t('cancel')"
></q-btn>
</div>
</q-form>
</q-card>
</q-dialog>
{% endblock %} {% block scripts %} {{ window_vars(user) }} {% endblock %} {% block scripts %} {{ window_vars(user) }}
<script src="{{ static_url_for('static', 'js/admin.js') }}"></script> <script src="{{ static_url_for('static', 'js/admin.js') }}"></script>
{% endblock %} {% endblock %}
+49 -14
View File
@@ -8,12 +8,19 @@
></div> ></div>
<div v-else class="col-12 col-md-4 col-lg-4 q-gutter-y-md"> <div v-else class="col-12 col-md-4 col-lg-4 q-gutter-y-md">
<div class="gt-sm"> <div class="gt-sm">
<h3 class="q-my-none" v-if="'{{SITE_TITLE}}' == 'LNbits'"> <h3
class="q-my-none"
v-if="'{{LNBITS_SHOW_HOME_PAGE_ELEMENTS}}' == 'True'"
>
{{SITE_TITLE}} {{SITE_TITLE}}
</h3> </h3>
<h5 class="q-my-md" v-if="'{{SITE_TITLE}}' == 'LNbits'"> <h5 class="q-my-md" v-if="'{{LNBITS_SHOW_HOME_PAGE_ELEMENTS}}' == 'True'">
{{SITE_TAGLINE}} {{SITE_TAGLINE}}
</h5> </h5>
<div
v-html="formatDescription"
v-if="'{{LNBITS_SHOW_HOME_PAGE_ELEMENTS}}' == 'True'"
></div>
</div> </div>
{% if lnurl and LNBITS_NEW_ACCOUNTS_ALLOWED and ("user-id-only" in {% if lnurl and LNBITS_NEW_ACCOUNTS_ALLOWED and ("user-id-only" in
LNBITS_AUTH_METHODS)%} LNBITS_AUTH_METHODS)%}
@@ -306,7 +313,7 @@
</div> </div>
<div <div
v-if="'{{SITE_TITLE}}' != 'LNbits'" v-if="'{{LNBITS_SHOW_HOME_PAGE_ELEMENTS}}' == 'False'"
class="col-12 col-md-5 col-lg-5 q-pt-xl" class="col-12 col-md-5 col-lg-5 q-pt-xl"
> >
<h3 class="q-my-none">{{SITE_TITLE}}</h3> <h3 class="q-my-none">{{SITE_TITLE}}</h3>
@@ -331,7 +338,7 @@
outline outline
color="grey" color="grey"
type="a" type="a"
href="https://legend.lnbits.com/paywall/GAqKguK5S8f6w5VNjS9DfK" href="https://demo.lnbits.com/lnurlp/link/fH59GD"
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
:label="$t('donate')" :label="$t('donate')"
@@ -499,23 +506,51 @@
</a> </a>
</div> </div>
</div> </div>
<div class="row">
<div class="col">
<a
href="https://phoenix.acinq.co/server"
target="_blank"
rel="noopener noreferrer"
>
<q-img
contain
:src="($q.dark.isActive) ? '{{ static_url_for('static', 'images/phoenixd.png') }}' : '{{ static_url_for('static', 'images/phoenixdl.png') }}'"
></q-img>
</a>
</div>
<div class="col q-pl-md"></div>
</div>
</div> </div>
</div> </div>
</div> </div>
{% if AD_SPACE %} {% for ADS in AD_SPACE %} {% set AD = ADS.split(';') %} </div>
<div class="col-6 col-sm-4 col-md-8 q-gutter-y-sm"> {% if AD_SPACE %}
<q-btn flat color="secondary" class="full-width q-mb-md" <div class="row justify-center">
>{{ AD_SPACE_TITLE }}</q-btn <q-btn flat color="secondary" class="full-width q-mb-md"
> >{{ AD_SPACE_TITLE }}</q-btn
>
<a href="{{ AD[0] }}" class="q-ma-md"> {% for ADS in AD_SPACE %} {% set AD = ADS.split(';') %}
<img v-if="($q.dark.isActive)" src="{{ AD[1] }}" style="max-width: 90%" /> <div class="flex flex-center column">
<img v-else src="{{ AD[2] }}" style="max-width: 90%" /> <a href="{{ AD[0] }}">
<img
v-if="($q.dark.isActive)"
src="{{ AD[1] }}"
style="max-width: 420px"
/>
<img v-else src="{{ AD[2] }}" style="max-width: 420px" />
</a> </a>
</div> </div>
{% endfor %} {% endif %}
{% endfor %}
</div> </div>
<div v-if="'{{SITE_TITLE}}' == 'LNbits'" class="row gt-sm q-mt-xl"> {% endif %}
<div
v-if="'{{LNBITS_SHOW_HOME_PAGE_ELEMENTS}}' == 'True'"
class="row gt-sm q-mt-xl"
>
<div class="col-1"></div> <div class="col-1"></div>
<div class="col-10 q-pl-xl"> <div class="col-10 q-pl-xl">
<span v-text="$t('lnbits_description')"></span> <span v-text="$t('lnbits_description')"></span>
+14 -246
View File
@@ -102,226 +102,11 @@
</div> </div>
</div> </div>
</q-card> </q-card>
<payment-list
<q-card :update="updatePayments"
:style="$q.screen.lt.md ? { :wallet="this.g.wallet"
background: $q.screen.lt.md ? 'none !important': '' :mobile-simple="mobileSimple"
, boxShadow: $q.screen.lt.md ? 'none !important': '' />
, marginTop: $q.screen.lt.md ? '0px !important': ''
} : ''"
>
<q-card-section>
<div class="row items-center no-wrap q-mb-sm">
<div class="col">
<h5
class="text-subtitle1 q-my-none"
:v-text="$t('transactions')"
></h5>
</div>
<div class="gt-sm col-auto">
<q-btn
flat
color="grey"
@click="exportCSV"
:label="$t('export_csv')"
></q-btn>
<q-btn
dense
flat
round
icon="show_chart"
color="grey"
@click="showChart"
>
<q-tooltip>
<span v-text="$t('chart_tooltip')"></span
></q-tooltip>
</q-btn>
</div>
</div>
<q-input
:style="$q.screen.lt.md ? {
display: mobileSimple ? 'none !important': ''
} : ''"
filled
dense
clearable
v-model="paymentsTable.search"
debounce="300"
:placeholder="$t('search_by_tag_memo_amount')"
class="q-mb-md"
>
</q-input>
<q-table
dense
flat
:data="paymentsOmitter"
:row-key="paymentTableRowKey"
:columns="paymentsTable.columns"
:pagination.sync="paymentsTable.pagination"
:no-data-label="$t('no_transactions')"
:filter="paymentsTable.search"
:loading="paymentsTable.loading"
:hide-header="mobileSimple"
:hide-bottom="mobileSimple"
@request="fetchPayments"
>
<template v-slot:header="props">
<q-tr :props="props">
<q-th auto-width></q-th>
<q-th
v-for="col in props.cols"
:key="col.name"
:props="props"
v-text="col.label"
></q-th>
</q-tr>
</template>
<template v-slot:body="props">
<q-tr :props="props">
<q-td auto-width class="text-center">
<q-icon
v-if="props.row.isPaid"
size="14px"
:name="props.row.isOut ? 'call_made' : 'call_received'"
:color="props.row.isOut ? 'pink' : 'green'"
@click="props.expand = !props.expand"
></q-icon>
<q-icon
v-else
name="settings_ethernet"
color="grey"
@click="props.expand = !props.expand"
>
<q-tooltip
><span v-text="$t('pending')"></span
></q-tooltip>
</q-icon>
</q-td>
<q-td
key="time"
:props="props"
style="white-space: normal; word-break: break-all"
>
<q-badge
v-if="props.row.tag"
color="yellow"
text-color="black"
>
<a
v-text="'#'+props.row.tag"
class="inherit"
:href="['/', props.row.tag].join('')"
></a>
</q-badge>
<span v-text="props.row.memo"></span>
<br />
<i>
<span v-text="props.row.dateFrom"></span>
<q-tooltip
><span v-text="props.row.date"></span
></q-tooltip>
</i>
</q-td>
<q-td
auto-width
key="amount"
v-if="'{{LNBITS_DENOMINATION}}' != 'sats'"
:props="props"
v-text="parseFloat(String(props.row.fsat).replaceAll(',', '')) / 100"
>
</q-td>
<q-td auto-width key="amount" v-else :props="props">
<span v-text="props.row.fsat"></span>
<br />
<i v-if="props.row.extra.wallet_fiat_currency">
<span
v-text="formatFiat(props.row.extra.wallet_fiat_currency, props.row.extra.wallet_fiat_amount)"
></span>
<br />
</i>
<i v-if="props.row.extra.fiat_currency">
<span
v-text="formatFiat(props.row.extra.fiat_currency, props.row.extra.fiat_amount)"
></span>
</i>
</q-td>
</q-tr>
<q-dialog v-model="props.expand" :props="props" position="top">
<q-card class="q-pa-lg q-pt-xl lnbits__dialog-card">
<div class="text-center q-mb-lg">
<div v-if="props.row.isIn && props.row.pending">
<q-icon name="settings_ethernet" color="grey"></q-icon>
<span v-text="$t('invoice_waiting')"></span>
<lnbits-payment-details
:payment="props.row"
></lnbits-payment-details>
<div
v-if="props.row.bolt11"
class="text-center q-mb-lg"
>
<a :href="'lightning:' + props.row.bolt11">
<q-responsive :ratio="1" class="q-mx-xl">
<lnbits-qrcode
:value="'lightning:' + props.row.bolt11.toUpperCase()"
></lnbits-qrcode>
</q-responsive>
</a>
</div>
<div class="row q-mt-lg">
<q-btn
outline
color="grey"
@click="copyText(props.row.bolt11)"
:label="$t('copy_invoice')"
></q-btn>
<q-btn
v-close-popup
flat
color="grey"
class="q-ml-auto"
:label="$t('close')"
></q-btn>
</div>
</div>
<div v-else-if="props.row.isPaid && props.row.isIn">
<q-icon
size="18px"
:name="'call_received'"
:color="'green'"
></q-icon>
<span v-text="$t('payment_received')"></span>
<lnbits-payment-details
:payment="props.row"
></lnbits-payment-details>
</div>
<div v-else-if="props.row.isPaid && props.row.isOut">
<q-icon
size="18px"
:name="'call_made'"
:color="'pink'"
></q-icon>
<span v-text="$t('payment_sent')"></span>
<lnbits-payment-details
:payment="props.row"
></lnbits-payment-details>
</div>
<div v-else-if="props.row.isOut && props.row.pending">
<q-icon name="settings_ethernet" color="grey"></q-icon>
<span v-text="$t('outgoing_payment_pending')"></span>
<lnbits-payment-details
:payment="props.row"
></lnbits-payment-details>
</div>
</div>
</q-card>
</q-dialog>
</template>
</q-table>
</q-card-section>
</q-card>
</div> </div>
{% if HIDE_API %} {% if HIDE_API %}
<div class="col-12 col-md-4 q-gutter-y-md"> <div class="col-12 col-md-4 q-gutter-y-md">
@@ -459,19 +244,21 @@
</q-list> </q-list>
</q-card-section> </q-card-section>
</q-card> </q-card>
{% endif %} {% if AD_SPACE %} {% for ADS in AD_SPACE %} {% set AD = {% endif %} {% if AD_SPACE %}
ADS.split(";") %}
<q-card> <q-card>
<q-card-section> <q-card-section>
<h6 class="text-subtitle1 q-mt-none q-mb-sm"> <h6 class="text-subtitle1 q-mt-none q-mb-sm">
{{ AD_SPACE_TITLE }} {{ AD_SPACE_TITLE }}
</h6> </h6>
</q-card-section> </q-card-section>
{% for ADS in AD_SPACE %} {% set AD = ADS.split(";") %}
<q-card-section class="q-pa-none"> <q-card-section class="q-pa-none">
<a <a
style="display: inline-block" style="display: inline-block"
href="{{ AD[0] }}" href="{{ AD[0] }}"
class="q-ma-md" class="q-ml-md q-mb-xs q-mr-md"
style="max-width: 80%"
> >
<img <img
style="max-width: 100%; height: auto" style="max-width: 100%; height: auto"
@@ -483,8 +270,10 @@
v-else v-else
src="{{ AD[2] }}" src="{{ AD[2] }}"
/> />
</a> </q-card-section></q-card </a> </q-card-section
>{% endfor %} {% endif %} >{% endfor %}
</q-card>
{% endif %}
</div> </div>
</div> </div>
@@ -873,27 +662,6 @@
</q-card> </q-card>
</q-dialog> </q-dialog>
<q-dialog v-model="paymentsChart.show" position="top">
<q-card class="q-pa-sm" style="width: 800px; max-width: unset">
<q-card-section>
<div class="row q-gutter-sm justify-between">
<div class="text-h6">Payments Chart</div>
<q-select
label="Group"
filled
dense
v-model="paymentsChart.group"
style="min-width: 120px"
:options="paymentsChart.groupOptions"
>
</q-select>
</div>
<canvas ref="canvas" width="600" height="400"></canvas>
</q-card-section>
</q-card>
</q-dialog>
<q-tabs <q-tabs
class="lt-md fixed-bottom left-0 right-0 bg-primary text-white shadow-2 z-top" class="lt-md fixed-bottom left-0 right-0 bg-primary text-white shadow-2 z-top"
active-class="px-0" active-class="px-0"
@@ -0,0 +1,23 @@
<q-dialog v-model="createUserDialog.show">
<q-card class="q-pa-lg q-pt-xl lnbits__dialog-card">
<p>Create User</p>
<div class="row">
<div class="col-12">
<q-form @submit="createUser">
<lnbits-dynamic-fields
:options="createUserDialog.fields"
v-model="createUserDialog.data"
></lnbits-dynamic-fields>
<div class="row q-mt-lg">
<q-btn v-close-popup unelevated color="primary" type="submit"
>Create</q-btn
>
<q-btn v-close-popup flat color="grey" class="q-ml-auto"
>Cancel</q-btn
>
</div>
</q-form>
</div>
</div>
</q-card>
</q-dialog>
@@ -0,0 +1,23 @@
<q-dialog v-model="createWalletDialog.show">
<q-card class="q-pa-lg q-pt-xl lnbits__dialog-card">
<p>Create Wallet</p>
<div class="row">
<div class="col-12">
<q-form @submit="createWallet">
<lnbits-dynamic-fields
:options="createWalletDialog.fields"
v-model="createUserDialog.data"
></lnbits-dynamic-fields>
<div class="row q-mt-lg">
<q-btn v-close-popup unelevated color="primary" type="submit"
>Create</q-btn
>
<q-btn v-close-popup flat color="grey" class="q-ml-auto"
>Cancel</q-btn
>
</div>
</q-form>
</div>
</div>
</q-card>
</q-dialog>
@@ -0,0 +1,49 @@
<q-dialog v-model="topupDialog.show" position="top">
<q-card class="q-pa-lg q-pt-xl lnbits__dialog-card">
<q-form class="q-gutter-md">
<p v-text="$t('topup_wallet')"></p>
<div class="row">
<div class="col-12">
<q-input
dense
type="text"
filled
v-model="wallet.id"
label="Wallet ID"
:hint="$t('topup_hint')"
></q-input>
<br />
</div>
<div class="col-12">
<q-input
dense
type="number"
filled
v-model="wallet.amount"
:label="$t('amount')"
></q-input>
</div>
</div>
<div class="row q-mt-lg">
<q-btn
:label="$t('topup')"
color="primary"
@click="topupWallet"
v-close-popup
></q-btn>
<q-btn
v-close-popup
flat
color="grey"
class="q-ml-auto"
:label="$t('cancel')"
></q-btn>
</div>
</q-form>
</q-card>
</q-dialog>
@@ -0,0 +1,106 @@
<q-dialog v-model="walletDialog.show">
<q-card class="q-pa-lg" style="width: 700px; max-width: 80vw">
<h2 class="text-h6 q-mb-md">Wallets</h2>
<q-dialog v-model="paymentDialog.show">
<q-card class="q-pa-lg" style="width: 700px; max-width: 80vw">
<payment-list :wallet="activeWallet" />
</q-card>
</q-dialog>
<q-table :data="wallets" :columns="walletTable.columns">
<template v-slot:header="props">
<q-tr :props="props">
<q-th auto-width></q-th>
<q-th
auto-width
v-for="col in props.cols"
v-text="col.label"
:key="col.name"
:props="props"
></q-th>
</q-tr>
</template>
<template v-slot:body="props">
<q-tr :props="props">
<q-td auto-width>
<q-btn
round
icon="menu"
size="sm"
color="secondary"
@click="showPayments(props.row.id)"
>
<q-tooltip>Show Payments</q-tooltip>
</q-btn>
<q-btn
v-if="!props.row.deleted"
round
icon="content_copy"
size="sm"
color="primary"
@click="copyText(props.row.id)"
>
<q-tooltip>Copy Wallet ID</q-tooltip>
</q-btn>
<lnbits-update-balance
v-if="!props.row.deleted"
:wallet_id="props.row.id"
:callback="topupCallback"
></lnbits-update-balance>
<q-btn
round
v-if="!props.row.deleted"
icon="vpn_key"
size="sm"
color="primary"
@click="copyText(props.row.adminkey)"
>
<q-tooltip>Copy Admin Key</q-tooltip>
</q-btn>
<q-btn
round
v-if="!props.row.deleted"
icon="vpn_key"
size="sm"
color="secondary"
@click="copyText(props.row.inkey)"
>
<q-tooltip>Copy Invoice Key</q-tooltip>
</q-btn>
<q-btn
round
v-if="props.row.deleted"
icon="toggle_off"
size="sm"
color="secondary"
@click="undeleteUserWallet(props.row.user, props.row.id)"
>
<q-tooltip>Undelete Wallet</q-tooltip>
</q-btn>
<q-btn
round
icon="delete"
size="sm"
color="negative"
@click="deleteUserWallet(props.row.user, props.row.id, props.row.deleted)"
>
<q-tooltip>Delete Wallet</q-tooltip>
</q-btn>
</q-td>
<q-td auto-width v-text="props.row.name"></q-td>
<q-td auto-width v-text="props.row.currency"></q-td>
<q-td auto-width v-text="formatSat(props.row.balance_msat)"></q-td>
<q-td auto-width v-text="props.row.deleted"></q-td>
</q-tr>
</template>
</q-table>
<div class="row q-mt-lg">
<q-btn
v-close-popup
flat
color="grey"
class="q-ml-auto"
:label="$t('close')"
></q-btn>
</div>
</q-card>
</q-dialog>
+116
View File
@@ -0,0 +1,116 @@
{% extends "base.html" %} {% from "macros.jinja" import window_vars with context
%} {% block page %} {% include "users/_walletDialog.html" %} {% include
"users/_topupDialog.html" %} {% include "users/_createUserDialog.html" %} {%
include "users/_createWalletDialog.html" %}
<h3 class="text-subtitle q-my-none" v-text="$t('users')"></h3>
<div class="row q-col-gutter-md justify-center">
<div class="col q-gutter-y-md" style="width: 300px">
<div style="width: 600px">
<canvas ref="chart1"></canvas>
</div>
</div>
</div>
<div class="row q-col-gutter-md justify-center">
<div class="col q-gutter-y-md">
<q-card>
<q-card-section>
<div class="row items-center no-wrap q-mb-sm">
<q-btn :label="$t('topup')" @click="topupDialog.show = true">
<q-tooltip
>{%raw%}{{ $t('add_funds_tooltip') }}{%endraw%}</q-tooltip
>
</q-btn>
</div>
<q-table
:data="users"
:row-key="usersTableRowKey"
:columns="usersTable.columns"
:pagination.sync="usersTable.pagination"
:no-data-label="$t('no_users')"
:filter="usersTable.search"
:loading="usersTable.loading"
@request="fetchUsers"
>
<template v-slot:header="props">
<q-tr :props="props">
<q-th auto-width></q-th>
<q-th
v-for="col in props.cols"
v-text="col.label"
:key="col.name"
:props="props"
></q-th>
</q-tr>
</template>
<template v-slot:body="props">
<q-tr auto-width :props="props">
<q-td>
<q-btn
round
icon="list"
size="sm"
color="secondary"
@click="fetchWallets(props.row.id)"
>
<q-tooltip>Show Wallets</q-tooltip>
</q-btn>
<q-btn
round
icon="content_copy"
size="sm"
color="primary"
@click="copyText(props.row.id)"
>
<q-tooltip>Copy User ID</q-tooltip>
</q-btn>
<q-btn
round
v-if="!props.row.is_super_user"
icon="build"
size="sm"
:color="props.row.is_admin ? 'primary' : ''"
@click="toggleAdmin(props.row.id)"
>
<q-tooltip>Toggle Admin</q-tooltip>
</q-btn>
<q-btn
round
v-if="props.row.is_super_user"
icon="build"
size="sm"
color="positive"
>
<q-tooltip>Super User</q-tooltip>
</q-btn>
<q-btn
round
icon="delete"
size="sm"
color="negative"
@click="deleteUser(props.row.id, props)"
>
<q-tooltip>Delete User</q-tooltip>
</q-btn>
</q-td>
<q-td
auto-width
v-text="formatSat(props.row.balance_msat)"
></q-td>
<q-td auto-width v-text="props.row.wallet_count"></q-td>
<q-td auto-width v-text="props.row.transaction_count"></q-td>
<q-td auto-width v-text="props.row.username"></q-td>
<q-td auto-width v-text="props.row.email"></q-td>
<q-td auto-width v-text="props.row.last_payment"></q-td>
</q-tr>
</template>
</q-table>
</q-card-section>
</q-card>
</div>
</div>
{% endblock %} {% block scripts %} {{ window_vars(user) }}
<script src="{{ static_url_for('static', 'js/users.js') }}"></script>
{% endblock %}
+2 -40
View File
@@ -8,14 +8,11 @@ from urllib.parse import urlparse
from fastapi import APIRouter, Depends from fastapi import APIRouter, Depends
from fastapi.responses import FileResponse from fastapi.responses import FileResponse
from starlette.exceptions import HTTPException
from lnbits.core.crud import get_wallet from lnbits.core.models import User
from lnbits.core.models import CreateTopup, User
from lnbits.core.services import ( from lnbits.core.services import (
get_balance_delta, get_balance_delta,
update_cached_settings, update_cached_settings,
update_wallet_balance,
) )
from lnbits.core.tasks import api_invoice_listeners from lnbits.core.tasks import api_invoice_listeners
from lnbits.decorators import check_admin, check_super_user from lnbits.decorators import check_admin, check_super_user
@@ -36,18 +33,7 @@ admin_router = APIRouter(tags=["Admin UI"], prefix="/admin")
dependencies=[Depends(check_admin)], dependencies=[Depends(check_admin)],
) )
async def api_auditor(): async def api_auditor():
try: return await get_balance_delta()
delta, node_balance, total_balance = await get_balance_delta()
return {
"delta_msats": int(delta),
"node_balance_msats": int(node_balance),
"lnbits_balance_msats": int(total_balance),
}
except Exception:
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail="Could not audit balance.",
)
@admin_router.get( @admin_router.get(
@@ -104,30 +90,6 @@ async def api_restart_server() -> dict[str, str]:
return {"status": "Success"} return {"status": "Success"}
@admin_router.put(
"/api/v1/topup",
name="Topup",
status_code=HTTPStatus.OK,
dependencies=[Depends(check_super_user)],
)
async def api_topup_balance(data: CreateTopup) -> dict[str, str]:
try:
await get_wallet(data.id)
except Exception:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="wallet does not exist."
)
if settings.lnbits_backend_wallet_class == "VoidWallet":
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="VoidWallet active"
)
await update_wallet_balance(wallet_id=data.id, amount=int(data.amount))
return {"status": "Success"}
@admin_router.get( @admin_router.get(
"/api/v1/backup", "/api/v1/backup",
status_code=HTTPStatus.OK, status_code=HTTPStatus.OK,
+10 -8
View File
@@ -25,8 +25,8 @@ from lnbits.core.models import (
from lnbits.decorators import ( from lnbits.decorators import (
WalletTypeInfo, WalletTypeInfo,
check_user_exists, check_user_exists,
get_key_type,
require_admin_key, require_admin_key,
require_invoice_key,
) )
from lnbits.lnurl import decode as lnurl_decode from lnbits.lnurl import decode as lnurl_decode
from lnbits.settings import settings from lnbits.settings import settings
@@ -67,7 +67,7 @@ async def api_wallets(user: User = Depends(check_user_exists)) -> List[BaseWalle
async def api_create_account(data: CreateWallet) -> Wallet: async def api_create_account(data: CreateWallet) -> Wallet:
if not settings.new_accounts_allowed: if not settings.new_accounts_allowed:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, status_code=HTTPStatus.FORBIDDEN,
detail="Account creation is disabled.", detail="Account creation is disabled.",
) )
account = await create_account() account = await create_account()
@@ -75,11 +75,13 @@ async def api_create_account(data: CreateWallet) -> Wallet:
@api_router.get("/api/v1/lnurlscan/{code}") @api_router.get("/api/v1/lnurlscan/{code}")
async def api_lnurlscan(code: str, wallet: WalletTypeInfo = Depends(get_key_type)): async def api_lnurlscan(
code: str, wallet: WalletTypeInfo = Depends(require_invoice_key)
):
try: try:
url = str(lnurl_decode(code)) url = str(lnurl_decode(code))
domain = urlparse(url).netloc domain = urlparse(url).netloc
except Exception: except Exception as exc:
# parse internet identifier (user@domain.com) # parse internet identifier (user@domain.com)
name_domain = code.split("@") name_domain = code.split("@")
if len(name_domain) == 2 and len(name_domain[1].split(".")) >= 2: if len(name_domain) == 2 and len(name_domain[1].split(".")) >= 2:
@@ -94,7 +96,7 @@ async def api_lnurlscan(code: str, wallet: WalletTypeInfo = Depends(get_key_type
else: else:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, detail="invalid lnurl" status_code=HTTPStatus.BAD_REQUEST, detail="invalid lnurl"
) ) from exc
# params is what will be returned to the client # params is what will be returned to the client
params: Dict = {"domain": domain} params: Dict = {"domain": domain}
@@ -119,14 +121,14 @@ async def api_lnurlscan(code: str, wallet: WalletTypeInfo = Depends(get_key_type
try: try:
data = json.loads(r.text) data = json.loads(r.text)
except json.decoder.JSONDecodeError: except json.decoder.JSONDecodeError as exc:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.SERVICE_UNAVAILABLE, status_code=HTTPStatus.SERVICE_UNAVAILABLE,
detail={ detail={
"domain": domain, "domain": domain,
"message": f"got invalid response '{r.text[:200]}'", "message": f"got invalid response '{r.text[:200]}'",
}, },
) ) from exc
try: try:
tag: str = data.get("tag") tag: str = data.get("tag")
@@ -185,7 +187,7 @@ async def api_lnurlscan(code: str, wallet: WalletTypeInfo = Depends(get_key_type
"domain": domain, "domain": domain,
"message": f"lnurl JSON response invalid: {exc}", "message": f"lnurl JSON response invalid: {exc}",
}, },
) ) from exc
return params return params
+49 -45
View File
@@ -68,11 +68,11 @@ async def login(data: LoginUsernamePassword) -> JSONResponse:
raise HTTPException(HTTP_401_UNAUTHORIZED, "Invalid credentials.") raise HTTPException(HTTP_401_UNAUTHORIZED, "Invalid credentials.")
return _auth_success_response(user.username, user.id) return _auth_success_response(user.username, user.id)
except HTTPException as e: except HTTPException as exc:
raise e raise exc
except Exception as e: except Exception as exc:
logger.debug(e) logger.debug(exc)
raise HTTPException(HTTP_500_INTERNAL_SERVER_ERROR, "Cannot login.") raise HTTPException(HTTP_500_INTERNAL_SERVER_ERROR, "Cannot login.") from exc
@auth_router.post("/usr", description="Login via the User ID") @auth_router.post("/usr", description="Login via the User ID")
@@ -86,11 +86,11 @@ async def login_usr(data: LoginUsr) -> JSONResponse:
raise HTTPException(HTTP_401_UNAUTHORIZED, "User ID does not exist.") raise HTTPException(HTTP_401_UNAUTHORIZED, "User ID does not exist.")
return _auth_success_response(user.username or "", user.id) return _auth_success_response(user.username or "", user.id)
except HTTPException as e: except HTTPException as exc:
raise e raise exc
except Exception as e: except Exception as exc:
logger.debug(e) logger.debug(exc)
raise HTTPException(HTTP_500_INTERNAL_SERVER_ERROR, "Cannot login.") raise HTTPException(HTTP_500_INTERNAL_SERVER_ERROR, "Cannot login.") from exc
@auth_router.get("/{provider}", description="SSO Provider") @auth_router.get("/{provider}", description="SSO Provider")
@@ -124,16 +124,16 @@ async def handle_oauth_token(request: Request, provider: str) -> RedirectRespons
user_id = decrypt_internal_message(provider_sso.state) user_id = decrypt_internal_message(provider_sso.state)
request.session.pop("user", None) request.session.pop("user", None)
return await _handle_sso_login(userinfo, user_id) return await _handle_sso_login(userinfo, user_id)
except HTTPException as e: except HTTPException as exc:
raise e raise exc
except ValueError as e: except ValueError as exc:
raise HTTPException(HTTP_403_FORBIDDEN, str(e)) raise HTTPException(HTTP_403_FORBIDDEN, str(exc)) from exc
except Exception as e: except Exception as exc:
logger.debug(e) logger.debug(exc)
raise HTTPException( raise HTTPException(
HTTP_500_INTERNAL_SERVER_ERROR, HTTP_500_INTERNAL_SERVER_ERROR,
f"Cannot authenticate user with {provider} Auth.", f"Cannot authenticate user with {provider} Auth.",
) ) from exc
@auth_router.post("/logout") @auth_router.post("/logout")
@@ -169,11 +169,13 @@ async def register(data: CreateUser) -> JSONResponse:
user = await create_user(data) user = await create_user(data)
return _auth_success_response(user.username) return _auth_success_response(user.username)
except ValueError as e: except ValueError as exc:
raise HTTPException(HTTP_403_FORBIDDEN, str(e)) raise HTTPException(HTTP_403_FORBIDDEN, str(exc)) from exc
except Exception as e: except Exception as exc:
logger.debug(e) logger.debug(exc)
raise HTTPException(HTTP_500_INTERNAL_SERVER_ERROR, "Cannot create user.") raise HTTPException(
HTTP_500_INTERNAL_SERVER_ERROR, "Cannot create user."
) from exc
@auth_router.put("/password") @auth_router.put("/password")
@@ -189,13 +191,13 @@ async def update_password(
try: try:
return await update_user_password(data) return await update_user_password(data)
except AssertionError as e: except AssertionError as exc:
raise HTTPException(HTTP_403_FORBIDDEN, str(e)) raise HTTPException(HTTP_403_FORBIDDEN, str(exc)) from exc
except Exception as e: except Exception as exc:
logger.debug(e) logger.debug(exc)
raise HTTPException( raise HTTPException(
HTTP_500_INTERNAL_SERVER_ERROR, "Cannot update user password." HTTP_500_INTERNAL_SERVER_ERROR, "Cannot update user password."
) ) from exc
@auth_router.put("/update") @auth_router.put("/update")
@@ -211,11 +213,13 @@ async def update(
try: try:
return await update_account(user.id, data.username, None, data.config) return await update_account(user.id, data.username, None, data.config)
except AssertionError as e: except AssertionError as exc:
raise HTTPException(HTTP_403_FORBIDDEN, str(e)) raise HTTPException(HTTP_403_FORBIDDEN, str(exc)) from exc
except Exception as e: except Exception as exc:
logger.debug(e) logger.debug(exc)
raise HTTPException(HTTP_500_INTERNAL_SERVER_ERROR, "Cannot update user.") raise HTTPException(
HTTP_500_INTERNAL_SERVER_ERROR, "Cannot update user."
) from exc
@auth_router.put("/first_install") @auth_router.put("/first_install")
@@ -237,13 +241,13 @@ async def first_install(data: UpdateSuperuserPassword) -> JSONResponse:
await update_user_password(super_user) await update_user_password(super_user)
settings.first_install = False settings.first_install = False
return _auth_success_response(username=super_user.username) return _auth_success_response(username=super_user.username)
except AssertionError as e: except AssertionError as exc:
raise HTTPException(HTTP_403_FORBIDDEN, str(e)) raise HTTPException(HTTP_403_FORBIDDEN, str(exc)) from exc
except Exception as e: except Exception as exc:
logger.debug(e) logger.debug(exc)
raise HTTPException( raise HTTPException(
HTTP_500_INTERNAL_SERVER_ERROR, "Cannot update user password." HTTP_500_INTERNAL_SERVER_ERROR, "Cannot update user password."
) ) from exc
async def _handle_sso_login(userinfo: OpenID, verified_user_id: Optional[str] = None): async def _handle_sso_login(userinfo: OpenID, verified_user_id: Optional[str] = None):
@@ -316,16 +320,16 @@ def _new_sso(provider: str) -> Optional[SSOBase]:
logger.warning(f"{provider} auth allowed but not configured.") logger.warning(f"{provider} auth allowed but not configured.")
return None return None
SSOProviderClass = _find_auth_provider_class(provider) sso_provider_class = _find_auth_provider_class(provider)
ssoProvider = SSOProviderClass( sso_provider = sso_provider_class(
client_id, client_secret, None, allow_insecure_http=True client_id, client_secret, None, allow_insecure_http=True
) )
if ( if (
discovery_url discovery_url
and getattr(ssoProvider, "discovery_url", discovery_url) != discovery_url and getattr(sso_provider, "discovery_url", discovery_url) != discovery_url
): ):
ssoProvider.discovery_url = discovery_url sso_provider.discovery_url = discovery_url
return ssoProvider return sso_provider
except Exception as e: except Exception as e:
logger.warning(e) logger.warning(e)
@@ -337,9 +341,9 @@ def _find_auth_provider_class(provider: str) -> Callable:
for module in sso_modules: for module in sso_modules:
try: try:
provider_module = importlib.import_module(f"{module}.{provider}") provider_module = importlib.import_module(f"{module}.{provider}")
ProviderClass = getattr(provider_module, f"{provider.title()}SSO") provider_class = getattr(provider_module, f"{provider.title()}SSO")
if ProviderClass: if provider_class:
return ProviderClass return provider_class
except Exception: except Exception:
pass pass
+29 -28
View File
@@ -1,3 +1,4 @@
from http import HTTPStatus
from typing import ( from typing import (
List, List,
Optional, Optional,
@@ -9,9 +10,6 @@ from fastapi import (
Depends, Depends,
HTTPException, HTTPException,
) )
from fastapi import (
status as HTTPStatus,
)
from loguru import logger from loguru import logger
from lnbits.core.db import core_app_extra from lnbits.core.db import core_app_extra
@@ -44,6 +42,7 @@ from ..crud import (
drop_extension_db, drop_extension_db,
get_dbversions, get_dbversions,
get_installed_extension, get_installed_extension,
get_installed_extensions,
) )
extension_router = APIRouter( extension_router = APIRouter(
@@ -105,10 +104,10 @@ async def api_install_extension(
ext_info.notify_upgrade() ext_info.notify_upgrade()
return extension return extension
except AssertionError as e: except AssertionError as exc:
raise HTTPException(HTTPStatus.BAD_REQUEST, str(e)) raise HTTPException(HTTPStatus.BAD_REQUEST, str(exc)) from exc
except Exception as ex: except Exception as exc:
logger.warning(ex) logger.warning(exc)
ext_info.clean_extension_files() ext_info.clean_extension_files()
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR, status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
@@ -116,7 +115,7 @@ async def api_install_extension(
f"Failed to install extension {ext_info.id} " f"Failed to install extension {ext_info.id} "
f"({ext_info.installed_version})." f"({ext_info.installed_version})."
), ),
) ) from exc
@extension_router.delete("/{ext_id}") @extension_router.delete("/{ext_id}")
@@ -125,9 +124,9 @@ async def api_uninstall_extension(
user: User = Depends(check_admin), user: User = Depends(check_admin),
access_token: Optional[str] = Depends(check_access_token), access_token: Optional[str] = Depends(check_access_token),
): ):
installable_extensions = await InstallableExtension.get_installable_extensions() installed_extensions = await get_installed_extensions()
extensions = [e for e in installable_extensions if e.id == ext_id] extensions = [e for e in installed_extensions if e.id == ext_id]
if len(extensions) == 0: if len(extensions) == 0:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, status_code=HTTPStatus.BAD_REQUEST,
@@ -137,7 +136,7 @@ async def api_uninstall_extension(
# check that other extensions do not depend on this one # check that other extensions do not depend on this one
for valid_ext_id in [ext.code for ext in get_valid_extensions()]: for valid_ext_id in [ext.code for ext in get_valid_extensions()]:
installed_ext = next( installed_ext = next(
(ext for ext in installable_extensions if ext.id == valid_ext_id), None (ext for ext in installed_extensions if ext.id == valid_ext_id), None
) )
if installed_ext and ext_id in installed_ext.dependencies: if installed_ext and ext_id in installed_ext.dependencies:
raise HTTPException( raise HTTPException(
@@ -160,10 +159,10 @@ async def api_uninstall_extension(
await delete_installed_extension(ext_id=ext_info.id) await delete_installed_extension(ext_id=ext_info.id)
logger.success(f"Extension '{ext_id}' uninstalled.") logger.success(f"Extension '{ext_id}' uninstalled.")
except Exception as ex: except Exception as exc:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(ex) status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(exc)
) ) from exc
@extension_router.get("/{ext_id}/releases", dependencies=[Depends(check_admin)]) @extension_router.get("/{ext_id}/releases", dependencies=[Depends(check_admin)])
@@ -184,10 +183,10 @@ async def get_extension_releases(ext_id: str):
return extension_releases return extension_releases
except Exception as ex: except Exception as exc:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(ex) status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(exc)
) ) from exc
@extension_router.put("/invoice", dependencies=[Depends(check_admin)]) @extension_router.put("/invoice", dependencies=[Depends(check_admin)])
@@ -217,11 +216,13 @@ async def get_extension_invoice(data: CreateExtension):
return payment_info return payment_info
except AssertionError as e: except AssertionError as exc:
raise HTTPException(HTTPStatus.BAD_REQUEST, str(e)) raise HTTPException(HTTPStatus.BAD_REQUEST, str(exc)) from exc
except Exception as ex: except Exception as exc:
logger.warning(ex) logger.warning(exc)
raise HTTPException(HTTPStatus.INTERNAL_SERVER_ERROR, "Cannot request invoice") raise HTTPException(
HTTPStatus.INTERNAL_SERVER_ERROR, "Cannot request invoice"
) from exc
@extension_router.get( @extension_router.get(
@@ -239,10 +240,10 @@ async def get_extension_release(org: str, repo: str, tag_name: str):
"is_version_compatible": config.is_version_compatible(), "is_version_compatible": config.is_version_compatible(),
"warning": config.warning, "warning": config.warning,
} }
except Exception as ex: except Exception as exc:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(ex) status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(exc)
) ) from exc
@extension_router.delete( @extension_router.delete(
@@ -263,9 +264,9 @@ async def delete_extension_db(ext_id: str):
except HTTPException as ex: except HTTPException as ex:
logger.error(ex) logger.error(ex)
raise ex raise ex
except Exception as ex: except Exception as exc:
logger.error(ex) logger.error(exc)
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR, status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail=f"Cannot delete data for extension '{ext_id}'", detail=f"Cannot delete data for extension '{ext_id}'",
) ) from exc
+37 -131
View File
@@ -1,40 +1,35 @@
import asyncio
import sys import sys
from http import HTTPStatus from http import HTTPStatus
from pathlib import Path from pathlib import Path
from typing import Annotated, List, Optional, Union from typing import Annotated, List, Optional, Union
from urllib.parse import urlparse from urllib.parse import urlparse
from fastapi import Cookie, Depends, Query, Request, status from fastapi import Cookie, Depends, Query, Request
from fastapi.exceptions import HTTPException from fastapi.exceptions import HTTPException
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse from fastapi.responses import FileResponse, HTMLResponse, RedirectResponse
from fastapi.routing import APIRouter from fastapi.routing import APIRouter
from loguru import logger from loguru import logger
from pydantic.types import UUID4 from pydantic.types import UUID4
from lnbits.core.db import core_app_extra, db from lnbits.core.db import core_app_extra
from lnbits.core.helpers import to_valid_user_id from lnbits.core.helpers import to_valid_user_id
from lnbits.core.models import User from lnbits.core.models import User
from lnbits.decorators import check_admin, check_user_exists from lnbits.decorators import check_admin, check_user_exists
from lnbits.helpers import template_renderer, url_for from lnbits.helpers import template_renderer
from lnbits.settings import settings from lnbits.settings import settings
from lnbits.wallets import get_wallet_class from lnbits.wallets import get_funding_source
from ...extension_manager import InstallableExtension, get_valid_extensions from ...extension_manager import InstallableExtension, get_valid_extensions
from ...utils.exchange_rates import allowed_currencies, currencies from ...utils.exchange_rates import allowed_currencies, currencies
from ..crud import ( from ..crud import (
create_account,
create_wallet, create_wallet,
get_balance_check,
get_dbversions, get_dbversions,
get_inactive_extensions, get_inactive_extensions,
get_installed_extensions, get_installed_extensions,
get_user, get_user,
save_balance_notify,
update_installed_extension_state, update_installed_extension_state,
update_user_extension, update_user_extension,
) )
from ..services import pay_invoice, redeem_lnurl_withdraw
generic_router = APIRouter( generic_router = APIRouter(
tags=["Core NON-API Website Routes"], include_in_schema=False tags=["Core NON-API Website Routes"], include_in_schema=False
@@ -176,9 +171,11 @@ async def extensions_install(
"extensions": extensions, "extensions": extensions,
}, },
) )
except Exception as e: except Exception as exc:
logger.warning(e) logger.warning(exc)
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e)) raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(exc)
) from exc
@generic_router.get( @generic_router.get(
@@ -243,115 +240,6 @@ async def account(
) )
@generic_router.get("/withdraw", response_class=JSONResponse)
async def lnurl_full_withdraw(request: Request):
usr_param = request.query_params.get("usr")
if not usr_param:
return {"status": "ERROR", "reason": "usr parameter not provided."}
user = await get_user(usr_param)
if not user:
return {"status": "ERROR", "reason": "User does not exist."}
wal_param = request.query_params.get("wal")
if not wal_param:
return {"status": "ERROR", "reason": "wal parameter not provided."}
wallet = user.get_wallet(wal_param)
if not wallet:
return {"status": "ERROR", "reason": "Wallet does not exist."}
return {
"tag": "withdrawRequest",
"callback": url_for("/withdraw/cb", external=True, usr=user.id, wal=wallet.id),
"k1": "0",
"minWithdrawable": 1000 if wallet.withdrawable_balance else 0,
"maxWithdrawable": wallet.withdrawable_balance,
"defaultDescription": (
f"{settings.lnbits_site_title} balance withdraw from {wallet.id[0:5]}"
),
"balanceCheck": url_for("/withdraw", external=True, usr=user.id, wal=wallet.id),
}
@generic_router.get("/withdraw/cb", response_class=JSONResponse)
async def lnurl_full_withdraw_callback(request: Request):
usr_param = request.query_params.get("usr")
if not usr_param:
return {"status": "ERROR", "reason": "usr parameter not provided."}
user = await get_user(usr_param)
if not user:
return {"status": "ERROR", "reason": "User does not exist."}
wal_param = request.query_params.get("wal")
if not wal_param:
return {"status": "ERROR", "reason": "wal parameter not provided."}
wallet = user.get_wallet(wal_param)
if not wallet:
return {"status": "ERROR", "reason": "Wallet does not exist."}
pr = request.query_params.get("pr")
if not pr:
return {"status": "ERROR", "reason": "payment_request not provided."}
async def pay():
try:
await pay_invoice(wallet_id=wallet.id, payment_request=pr)
except Exception:
pass
asyncio.create_task(pay())
balance_notify = request.query_params.get("balanceNotify")
if balance_notify:
await save_balance_notify(wallet.id, balance_notify)
return {"status": "OK"}
@generic_router.get("/withdraw/notify/{service}")
async def lnurl_balance_notify(request: Request, service: str):
wal_param = request.query_params.get("wal")
if not wal_param:
return {"status": "ERROR", "reason": "wal parameter not provided."}
bc = await get_balance_check(wal_param, service)
if bc:
await redeem_lnurl_withdraw(bc.wallet, bc.url)
@generic_router.get(
"/lnurlwallet", response_class=RedirectResponse, name="core.lnurlwallet"
)
async def lnurlwallet(request: Request):
async with db.connect() as conn:
account = await create_account(conn=conn)
user = await get_user(account.id, conn=conn)
assert user, "Newly created user not found."
wallet = await create_wallet(user_id=user.id, conn=conn)
lightning_param = request.query_params.get("lightning")
if not lightning_param:
return {"status": "ERROR", "reason": "lightning parameter not provided."}
asyncio.create_task(
redeem_lnurl_withdraw(
wallet.id,
lightning_param,
"LNbits initial funding: voucher redeem.",
{"tag": "lnurlwallet"},
5, # wait 5 seconds before sending the invoice to the service
)
)
return RedirectResponse(
f"/wallet?usr={user.id}&wal={wallet.id}",
status_code=status.HTTP_307_TEMPORARY_REDIRECT,
)
@generic_router.get("/service-worker.js") @generic_router.get("/service-worker.js")
async def service_worker(request: Request): async def service_worker(request: Request):
return template_renderer().TemplateResponse( return template_renderer().TemplateResponse(
@@ -452,8 +340,8 @@ async def node(request: Request, user: User = Depends(check_admin)):
if not settings.lnbits_node_ui: if not settings.lnbits_node_ui:
raise HTTPException(status_code=HTTPStatus.SERVICE_UNAVAILABLE) raise HTTPException(status_code=HTTPStatus.SERVICE_UNAVAILABLE)
WALLET = get_wallet_class() funding_source = get_funding_source()
_, balance = await WALLET.status() _, balance = await funding_source.status()
return template_renderer().TemplateResponse( return template_renderer().TemplateResponse(
request, request,
@@ -472,8 +360,8 @@ async def node_public(request: Request):
if not settings.lnbits_public_node_ui: if not settings.lnbits_public_node_ui:
raise HTTPException(status_code=HTTPStatus.SERVICE_UNAVAILABLE) raise HTTPException(status_code=HTTPStatus.SERVICE_UNAVAILABLE)
WALLET = get_wallet_class() funding_source = get_funding_source()
_, balance = await WALLET.status() _, balance = await funding_source.status()
return template_renderer().TemplateResponse( return template_renderer().TemplateResponse(
request, request,
@@ -486,12 +374,12 @@ async def node_public(request: Request):
@generic_router.get("/admin", response_class=HTMLResponse) @generic_router.get("/admin", response_class=HTMLResponse)
async def index(request: Request, user: User = Depends(check_admin)): async def admin_index(request: Request, user: User = Depends(check_admin)):
if not settings.lnbits_admin_ui: if not settings.lnbits_admin_ui:
raise HTTPException(status_code=HTTPStatus.NOT_FOUND) raise HTTPException(status_code=HTTPStatus.NOT_FOUND)
WALLET = get_wallet_class() funding_source = get_funding_source()
_, balance = await WALLET.status() _, balance = await funding_source.status()
return template_renderer().TemplateResponse( return template_renderer().TemplateResponse(
request, request,
@@ -505,13 +393,31 @@ async def index(request: Request, user: User = Depends(check_admin)):
) )
@generic_router.get("/users", response_class=HTMLResponse)
async def users_index(request: Request, user: User = Depends(check_admin)):
if not settings.lnbits_admin_ui:
raise HTTPException(status_code=HTTPStatus.NOT_FOUND)
return template_renderer().TemplateResponse(
"users/index.html",
{
"request": request,
"user": user.dict(),
"settings": settings.dict(),
"currencies": list(currencies.keys()),
},
)
@generic_router.get("/uuidv4/{hex_value}") @generic_router.get("/uuidv4/{hex_value}")
async def hex_to_uuid4(hex_value: str): async def hex_to_uuid4(hex_value: str):
try: try:
user_id = to_valid_user_id(hex_value).hex user_id = to_valid_user_id(hex_value).hex
return RedirectResponse(url=f"/wallet?usr={user_id}") return RedirectResponse(url=f"/wallet?usr={user_id}")
except Exception as e: except Exception as exc:
raise HTTPException(status_code=HTTPStatus.BAD_REQUEST, detail=str(e)) raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, detail=str(exc)
) from exc
async def toggle_extension(extension_to_enable, extension_to_disable, user_id): async def toggle_extension(extension_to_enable, extension_to_disable, user_id):
+7 -5
View File
@@ -27,8 +27,8 @@ from ...utils.cache import cache
def require_node(): def require_node():
NODE = get_node_class() node_class = get_node_class()
if not NODE: if not node_class:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.NOT_IMPLEMENTED, status_code=HTTPStatus.NOT_IMPLEMENTED,
detail="Active backend does not implement Node API", detail="Active backend does not implement Node API",
@@ -38,7 +38,7 @@ def require_node():
status_code=HTTPStatus.SERVICE_UNAVAILABLE, status_code=HTTPStatus.SERVICE_UNAVAILABLE,
detail="Not enabled", detail="Not enabled",
) )
return NODE return node_class
def check_public(): def check_public():
@@ -195,5 +195,7 @@ async def api_get_1ml_stats(node: Node = Depends(require_node)) -> Optional[Node
try: try:
r.raise_for_status() r.raise_for_status()
return r.json()["noderank"] return r.json()["noderank"]
except httpx.HTTPStatusError: except httpx.HTTPStatusError as exc:
raise HTTPException(status_code=404, detail="Node not found on 1ml.com") raise HTTPException(
status_code=404, detail="Node not found on 1ml.com"
) from exc
+57 -81
View File
@@ -13,6 +13,7 @@ from fastapi import (
Depends, Depends,
Header, Header,
HTTPException, HTTPException,
Query,
Request, Request,
) )
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
@@ -25,12 +26,11 @@ from lnbits.core.models import (
CreateInvoice, CreateInvoice,
CreateLnurl, CreateLnurl,
DecodePayment, DecodePayment,
KeyType,
Payment, Payment,
PaymentFilters, PaymentFilters,
PaymentHistoryPoint, PaymentHistoryPoint,
Query,
Wallet, Wallet,
WalletType,
) )
from lnbits.db import Filters, Page from lnbits.db import Filters, Page
from lnbits.decorators import ( from lnbits.decorators import (
@@ -40,7 +40,7 @@ from lnbits.decorators import (
require_admin_key, require_admin_key,
require_invoice_key, require_invoice_key,
) )
from lnbits.helpers import generate_filter_params_openapi, url_for from lnbits.helpers import generate_filter_params_openapi
from lnbits.lnurl import decode as lnurl_decode from lnbits.lnurl import decode as lnurl_decode
from lnbits.settings import settings from lnbits.settings import settings
from lnbits.utils.exchange_rates import fiat_amount_as_satoshis from lnbits.utils.exchange_rates import fiat_amount_as_satoshis
@@ -52,12 +52,9 @@ from ..crud import (
get_payments_paginated, get_payments_paginated,
get_standalone_payment, get_standalone_payment,
get_wallet_for_key, get_wallet_for_key,
save_balance_check,
update_pending_payments, update_pending_payments,
) )
from ..services import ( from ..services import (
InvoiceFailure,
PaymentFailure,
check_transaction_status, check_transaction_status,
create_invoice, create_invoice,
fee_reserve_total, fee_reserve_total,
@@ -134,55 +131,47 @@ async def api_payments_create_invoice(data: CreateInvoice, wallet: Wallet):
if data.description_hash: if data.description_hash:
try: try:
description_hash = bytes.fromhex(data.description_hash) description_hash = bytes.fromhex(data.description_hash)
except ValueError: except ValueError as exc:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, status_code=HTTPStatus.BAD_REQUEST,
detail="'description_hash' must be a valid hex string", detail="'description_hash' must be a valid hex string",
) ) from exc
if data.unhashed_description: if data.unhashed_description:
try: try:
unhashed_description = bytes.fromhex(data.unhashed_description) unhashed_description = bytes.fromhex(data.unhashed_description)
except ValueError: except ValueError as exc:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, status_code=HTTPStatus.BAD_REQUEST,
detail="'unhashed_description' must be a valid hex string", detail="'unhashed_description' must be a valid hex string",
) ) from exc
# do not save memo if description_hash or unhashed_description is set # do not save memo if description_hash or unhashed_description is set
memo = "" memo = ""
async with db.connect() as conn: async with db.connect() as conn:
try: payment_hash, payment_request = await create_invoice(
payment_hash, payment_request = await create_invoice( wallet_id=wallet.id,
wallet_id=wallet.id, amount=data.amount,
amount=data.amount, memo=memo,
memo=memo, currency=data.unit,
currency=data.unit, description_hash=description_hash,
description_hash=description_hash, unhashed_description=unhashed_description,
unhashed_description=unhashed_description, expiry=data.expiry,
expiry=data.expiry, extra=data.extra,
extra=data.extra, webhook=data.webhook,
webhook=data.webhook, internal=data.internal,
internal=data.internal, conn=conn,
conn=conn, )
) # NOTE: we get the checking_id with a seperate query because create_invoice
# NOTE: we get the checking_id with a seperate query because create_invoice # does not return it and it would be a big hustle to change its return type
# does not return it and it would be a big hustle to change its return type # (used across extensions)
# (used across extensions) payment_db = await get_standalone_payment(payment_hash, conn=conn)
payment_db = await get_standalone_payment(payment_hash, conn=conn) assert payment_db is not None, "payment not found"
assert payment_db is not None, "payment not found" checking_id = payment_db.checking_id
checking_id = payment_db.checking_id
except InvoiceFailure as e:
raise HTTPException(status_code=520, detail=str(e))
except Exception as exc:
raise exc
invoice = bolt11.decode(payment_request) invoice = bolt11.decode(payment_request)
lnurl_response: Union[None, bool, str] = None lnurl_response: Union[None, bool, str] = None
if data.lnurl_callback: if data.lnurl_callback:
if data.lnurl_balance_check is not None:
await save_balance_check(wallet.id, data.lnurl_balance_check)
headers = {"User-Agent": settings.user_agent} headers = {"User-Agent": settings.user_agent}
async with httpx.AsyncClient(headers=headers) as client: async with httpx.AsyncClient(headers=headers) as client:
try: try:
@@ -190,11 +179,6 @@ async def api_payments_create_invoice(data: CreateInvoice, wallet: Wallet):
data.lnurl_callback, data.lnurl_callback,
params={ params={
"pr": payment_request, "pr": payment_request,
"balanceNotify": url_for(
f"/withdraw/notify/{urlparse(data.lnurl_callback).netloc}",
external=True,
wal=wallet.id,
),
}, },
timeout=10, timeout=10,
) )
@@ -213,32 +197,9 @@ async def api_payments_create_invoice(data: CreateInvoice, wallet: Wallet):
return { return {
"payment_hash": invoice.payment_hash, "payment_hash": invoice.payment_hash,
"payment_request": payment_request, "payment_request": payment_request,
"lnurl_response": lnurl_response,
# maintain backwards compatibility with API clients: # maintain backwards compatibility with API clients:
"checking_id": checking_id, "checking_id": checking_id,
"lnurl_response": lnurl_response,
}
async def api_payments_pay_invoice(
bolt11: str, wallet: Wallet, extra: Optional[dict] = None
):
try:
payment_hash = await pay_invoice(
wallet_id=wallet.id, payment_request=bolt11, extra=extra
)
except ValueError as e:
raise HTTPException(status_code=HTTPStatus.BAD_REQUEST, detail=str(e))
except PermissionError as e:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail=str(e))
except PaymentFailure as e:
raise HTTPException(status_code=520, detail=str(e))
except Exception as exc:
raise exc
return {
"payment_hash": payment_hash,
# maintain backwards compatibility with API clients:
"checking_id": payment_hash,
} }
@@ -254,23 +215,37 @@ async def api_payments_pay_invoice(
field to supply the BOLT11 invoice to be paid. field to supply the BOLT11 invoice to be paid.
""", """,
status_code=HTTPStatus.CREATED, status_code=HTTPStatus.CREATED,
responses={
400: {"description": "Invalid BOLT11 string or missing fields."},
401: {"description": "Invoice (or Admin) key required."},
520: {"description": "Payment or Invoice error."},
},
) )
async def api_payments_create( async def api_payments_create(
wallet: WalletTypeInfo = Depends(require_invoice_key), wallet: WalletTypeInfo = Depends(require_invoice_key),
invoiceData: CreateInvoice = Body(...), invoice_data: CreateInvoice = Body(...),
): ):
if invoiceData.out is True and wallet.wallet_type == WalletType.admin: if invoice_data.out is True and wallet.key_type == KeyType.admin:
if not invoiceData.bolt11: if not invoice_data.bolt11:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, status_code=HTTPStatus.BAD_REQUEST,
detail="BOLT11 string is invalid or not given", detail="BOLT11 string is invalid or not given",
) )
return await api_payments_pay_invoice(
invoiceData.bolt11, wallet.wallet, invoiceData.extra payment_hash = await pay_invoice(
) # admin key wallet_id=wallet.wallet.id,
elif not invoiceData.out: payment_request=invoice_data.bolt11,
extra=invoice_data.extra,
)
return {
"payment_hash": payment_hash,
# maintain backwards compatibility with API clients:
"checking_id": payment_hash,
}
elif not invoice_data.out:
# invoice key # invoice key
return await api_payments_create_invoice(invoiceData, wallet.wallet) return await api_payments_create_invoice(invoice_data, wallet.wallet)
else: else:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.UNAUTHORIZED, status_code=HTTPStatus.UNAUTHORIZED,
@@ -316,11 +291,11 @@ async def api_payments_pay_lnurl(
if r.is_error: if r.is_error:
raise httpx.ConnectError("LNURL callback connection error") raise httpx.ConnectError("LNURL callback connection error")
r.raise_for_status() r.raise_for_status()
except (httpx.ConnectError, httpx.RequestError): except (httpx.ConnectError, httpx.RequestError) as exc:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, status_code=HTTPStatus.BAD_REQUEST,
detail=f"Failed to connect to {domain}.", detail=f"Failed to connect to {domain}.",
) ) from exc
params = json.loads(r.text) params = json.loads(r.text)
if params.get("status") == "ERROR": if params.get("status") == "ERROR":
@@ -386,7 +361,7 @@ async def subscribe_wallet_invoices(request: Request, wallet: Wallet):
api_invoice_listeners[uid] = payment_queue api_invoice_listeners[uid] = payment_queue
try: try:
while True: while settings.lnbits_running:
if await request.is_disconnected(): if await request.is_disconnected():
await request.close() await request.close()
break break
@@ -415,10 +390,10 @@ async def api_payments_sse(
# TODO: refactor this route into a public and admin one # TODO: refactor this route into a public and admin one
@payment_router.get("/{payment_hash}") @payment_router.get("/{payment_hash}")
async def api_payment(payment_hash, X_Api_Key: Optional[str] = Header(None)): async def api_payment(payment_hash, x_api_key: Optional[str] = Header(None)):
# We use X_Api_Key here because we want this call to work with and without keys # We use X_Api_Key here because we want this call to work with and without keys
# If a valid key is given, we also return the field "details", otherwise not # If a valid key is given, we also return the field "details", otherwise not
wallet = await get_wallet_for_key(X_Api_Key) if isinstance(X_Api_Key, str) else None wallet = await get_wallet_for_key(x_api_key) if isinstance(x_api_key, str) else None
payment = await get_standalone_payment( payment = await get_standalone_payment(
payment_hash, wallet_id=wallet.id if wallet else None payment_hash, wallet_id=wallet.id if wallet else None
@@ -441,7 +416,7 @@ async def api_payment(payment_hash, X_Api_Key: Optional[str] = Header(None)):
return {"paid": True, "preimage": payment.preimage} return {"paid": True, "preimage": payment.preimage}
try: try:
await payment.check_status() status = await payment.check_status()
except Exception: except Exception:
if wallet and wallet.id == payment.wallet_id: if wallet and wallet.id == payment.wallet_id:
return {"paid": False, "details": payment} return {"paid": False, "details": payment}
@@ -450,6 +425,7 @@ async def api_payment(payment_hash, X_Api_Key: Optional[str] = Header(None)):
if wallet and wallet.id == payment.wallet_id: if wallet and wallet.id == payment.wallet_id:
return { return {
"paid": not payment.pending, "paid": not payment.pending,
"status": f"{status!s}",
"preimage": payment.preimage, "preimage": payment.preimage,
"details": payment, "details": payment,
} }
@@ -468,6 +444,6 @@ async def api_payments_decode(data: DecodePayment) -> JSONResponse:
return JSONResponse(invoice.data) return JSONResponse(invoice.data)
except Exception as exc: except Exception as exc:
return JSONResponse( return JSONResponse(
{"message": f"Failed to decode: {str(exc)}"}, {"message": f"Failed to decode: {exc!s}"},
status_code=HTTPStatus.BAD_REQUEST, status_code=HTTPStatus.BAD_REQUEST,
) )
+3 -3
View File
@@ -27,10 +27,10 @@ async def api_public_payment_longpolling(payment_hash):
invoice = bolt11.decode(payment.bolt11) invoice = bolt11.decode(payment.bolt11)
if invoice.has_expired(): if invoice.has_expired():
return {"status": "expired"} return {"status": "expired"}
except Exception: except Exception as exc:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, detail="Invalid bolt11 invoice." status_code=HTTPStatus.BAD_REQUEST, detail="Invalid bolt11 invoice."
) ) from exc
payment_queue = asyncio.Queue(0) payment_queue = asyncio.Queue(0)
@@ -50,7 +50,7 @@ async def api_public_payment_longpolling(payment_hash):
cancel_scope.cancel() cancel_scope.cancel()
cancel_scope = asyncio.create_task(payment_info_receiver()) cancel_scope = asyncio.create_task(payment_info_receiver())
asyncio.create_task(timeouter(cancel_scope)) asyncio.create_task(timeouter(cancel_scope)) # noqa: RUF006
if response: if response:
return response return response
+6 -6
View File
@@ -38,10 +38,10 @@ async def api_create_tinyurl(
if tinyurl.wallet == wallet.wallet.id: if tinyurl.wallet == wallet.wallet.id:
return tinyurl return tinyurl
return await create_tinyurl(url, endless, wallet.wallet.id) return await create_tinyurl(url, endless, wallet.wallet.id)
except Exception: except Exception as exc:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, detail="Unable to create tinyurl" status_code=HTTPStatus.BAD_REQUEST, detail="Unable to create tinyurl"
) ) from exc
@tinyurl_router.get( @tinyurl_router.get(
@@ -60,10 +60,10 @@ async def api_get_tinyurl(
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="Wrong key provided." status_code=HTTPStatus.FORBIDDEN, detail="Wrong key provided."
) )
except Exception: except Exception as exc:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Unable to fetch tinyurl" status_code=HTTPStatus.NOT_FOUND, detail="Unable to fetch tinyurl"
) ) from exc
@tinyurl_router.delete( @tinyurl_router.delete(
@@ -83,10 +83,10 @@ async def api_delete_tinyurl(
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="Wrong key provided." status_code=HTTPStatus.FORBIDDEN, detail="Wrong key provided."
) )
except Exception: except Exception as exc:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, detail="Unable to delete" status_code=HTTPStatus.BAD_REQUEST, detail="Unable to delete"
) ) from exc
@tinyurl_router.get( @tinyurl_router.get(
+159
View File
@@ -0,0 +1,159 @@
from http import HTTPStatus
from typing import List
from fastapi import APIRouter, Depends
from starlette.exceptions import HTTPException
from lnbits.core.crud import (
delete_account,
delete_wallet,
force_delete_wallet,
get_accounts,
get_wallet,
get_wallets,
update_admin_settings,
)
from lnbits.core.models import (
Account,
AccountFilters,
CreateTopup,
User,
Wallet,
)
from lnbits.core.services import update_wallet_balance
from lnbits.db import Filters, Page
from lnbits.decorators import check_admin, check_super_user, parse_filters
from lnbits.helpers import generate_filter_params_openapi
from lnbits.settings import EditableSettings, settings
users_router = APIRouter(prefix="/users/api/v1", dependencies=[Depends(check_admin)])
@users_router.get(
"/user",
name="get accounts",
summary="Get paginated list of accounts",
openapi_extra=generate_filter_params_openapi(AccountFilters),
)
async def api_get_users(
filters: Filters = Depends(parse_filters(AccountFilters)),
) -> Page[Account]:
try:
filtered = await get_accounts(filters=filters)
for user in filtered.data:
user.is_super_user = user.id == settings.super_user
user.is_admin = user.id in settings.lnbits_admin_users or user.is_super_user
return filtered
except Exception as exc:
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail=f"Could not fetch users. {exc!s}",
) from exc
@users_router.delete("/user/{user_id}", status_code=HTTPStatus.OK)
async def api_users_delete_user(
user_id: str, user: User = Depends(check_admin)
) -> None:
try:
wallets = await get_wallets(user_id)
if len(wallets) > 0:
raise Exception("Cannot delete user with wallets.")
if user_id == settings.super_user:
raise Exception("Cannot delete super user.")
if user_id in settings.lnbits_admin_users and not user.super_user:
raise Exception("Only super_user can delete admin user.")
await delete_account(user_id)
except Exception as exc:
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail=f"{exc!s}",
) from exc
@users_router.get("/user/{user_id}/admin", dependencies=[Depends(check_super_user)])
async def api_users_toggle_admin(user_id: str) -> None:
try:
if user_id == settings.super_user:
raise Exception("Cannot change super user.")
if user_id in settings.lnbits_admin_users:
settings.lnbits_admin_users.remove(user_id)
else:
settings.lnbits_admin_users.append(user_id)
update_settings = EditableSettings(
lnbits_admin_users=settings.lnbits_admin_users
)
await update_admin_settings(update_settings)
except Exception as exc:
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail=f"Could not update admin settings. {exc}",
) from exc
@users_router.get("/user/{user_id}/wallet")
async def api_users_get_user_wallet(user_id: str) -> List[Wallet]:
try:
return await get_wallets(user_id)
except Exception as exc:
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail=f"Could not fetch user wallets. {exc}",
) from exc
@users_router.get("/user/{user_id}/wallet/{wallet}/undelete")
async def api_users_undelete_user_wallet(user_id: str, wallet: str) -> None:
try:
wal = await get_wallet(wallet)
if not wal:
raise Exception("Wallet does not exist.")
if user_id != wal.user:
raise Exception("Wallet does not belong to user.")
if wal.deleted:
await delete_wallet(user_id=user_id, wallet_id=wallet, deleted=False)
except Exception as exc:
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail=f"{exc!s}",
) from exc
@users_router.delete("/user/{user_id}/wallet/{wallet}")
async def api_users_delete_user_wallet(user_id: str, wallet: str) -> None:
try:
wal = await get_wallet(wallet)
if not wal:
raise Exception("Wallet does not exist.")
if wal.deleted:
await force_delete_wallet(wallet)
await delete_wallet(user_id=user_id, wallet_id=wallet)
except Exception as exc:
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail=f"{exc!s}",
) from exc
@users_router.put(
"/topup",
name="Topup",
status_code=HTTPStatus.OK,
dependencies=[Depends(check_super_user)],
)
async def api_topup_balance(data: CreateTopup) -> dict[str, str]:
try:
await get_wallet(data.id)
if settings.lnbits_backend_wallet_class == "VoidWallet":
raise Exception("VoidWallet active")
await update_wallet_balance(wallet_id=data.id, amount=int(data.amount))
return {"status": "Success"}
except Exception as exc:
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=f"{exc!s}"
) from exc
+2 -2
View File
@@ -8,8 +8,8 @@ from fastapi import (
from lnbits.core.models import ( from lnbits.core.models import (
CreateWallet, CreateWallet,
KeyType,
Wallet, Wallet,
WalletType,
) )
from lnbits.decorators import ( from lnbits.decorators import (
WalletTypeInfo, WalletTypeInfo,
@@ -28,7 +28,7 @@ wallet_router = APIRouter(prefix="/api/v1/wallet", tags=["Wallet"])
@wallet_router.get("") @wallet_router.get("")
async def api_wallet(wallet: WalletTypeInfo = Depends(get_key_type)): async def api_wallet(wallet: WalletTypeInfo = Depends(get_key_type)):
if wallet.wallet_type == WalletType.admin: if wallet.key_type == KeyType.admin:
return { return {
"id": wallet.wallet.id, "id": wallet.wallet.id,
"name": wallet.wallet.name, "name": wallet.wallet.name,
+9 -7
View File
@@ -4,9 +4,11 @@ from fastapi import (
WebSocketDisconnect, WebSocketDisconnect,
) )
from lnbits.settings import settings
from ..services import ( from ..services import (
websocketManager, websocket_manager,
websocketUpdater, websocket_updater,
) )
websocket_router = APIRouter(prefix="/api/v1/ws", tags=["Websocket"]) websocket_router = APIRouter(prefix="/api/v1/ws", tags=["Websocket"])
@@ -14,18 +16,18 @@ websocket_router = APIRouter(prefix="/api/v1/ws", tags=["Websocket"])
@websocket_router.websocket("/{item_id}") @websocket_router.websocket("/{item_id}")
async def websocket_connect(websocket: WebSocket, item_id: str): async def websocket_connect(websocket: WebSocket, item_id: str):
await websocketManager.connect(websocket, item_id) await websocket_manager.connect(websocket, item_id)
try: try:
while True: while settings.lnbits_running:
await websocket.receive_text() await websocket.receive_text()
except WebSocketDisconnect: except WebSocketDisconnect:
websocketManager.disconnect(websocket) websocket_manager.disconnect(websocket)
@websocket_router.post("/{item_id}") @websocket_router.post("/{item_id}")
async def websocket_update_post(item_id: str, data: str): async def websocket_update_post(item_id: str, data: str):
try: try:
await websocketUpdater(item_id, data) await websocket_updater(item_id, data)
return {"sent": True, "data": data} return {"sent": True, "data": data}
except Exception: except Exception:
return {"sent": False, "data": data} return {"sent": False, "data": data}
@@ -34,7 +36,7 @@ async def websocket_update_post(item_id: str, data: str):
@websocket_router.get("/{item_id}/{data}") @websocket_router.get("/{item_id}/{data}")
async def websocket_update_get(item_id: str, data: str): async def websocket_update_get(item_id: str, data: str):
try: try:
await websocketUpdater(item_id, data) await websocket_updater(item_id, data)
return {"sent": True, "data": data} return {"sent": True, "data": data}
except Exception: except Exception:
return {"sent": False, "data": data} return {"sent": False, "data": data}
+19 -19
View File
@@ -8,7 +8,7 @@ import time
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from enum import Enum from enum import Enum
from sqlite3 import Row from sqlite3 import Row
from typing import Any, Generic, List, Literal, Optional, Type, TypeVar from typing import Any, Generic, Literal, Optional, TypeVar
from loguru import logger from loguru import logger
from pydantic import BaseModel, ValidationError, root_validator from pydantic import BaseModel, ValidationError, root_validator
@@ -140,14 +140,14 @@ class Connection(Compat):
def rewrite_values(self, values): def rewrite_values(self, values):
# strip html # strip html
CLEANR = re.compile("<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});") clean_regex = re.compile("<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});")
# tuple to list and back to tuple # tuple to list and back to tuple
raw_values = [values] if isinstance(values, str) else list(values) raw_values = [values] if isinstance(values, str) else list(values)
values = [] values = []
for raw_value in raw_values: for raw_value in raw_values:
if isinstance(raw_value, str): if isinstance(raw_value, str):
values.append(re.sub(CLEANR, "", raw_value)) values.append(re.sub(clean_regex, "", raw_value))
elif isinstance(raw_value, datetime.datetime): elif isinstance(raw_value, datetime.datetime):
ts = raw_value.timestamp() ts = raw_value.timestamp()
if self.type == SQLITE: if self.type == SQLITE:
@@ -175,11 +175,11 @@ class Connection(Compat):
async def fetch_page( async def fetch_page(
self, self,
query: str, query: str,
where: Optional[List[str]] = None, where: Optional[list[str]] = None,
values: Optional[List[str]] = None, values: Optional[list[str]] = None,
filters: Optional[Filters] = None, filters: Optional[Filters] = None,
model: Optional[Type[TRowModel]] = None, model: Optional[type[TRowModel]] = None,
group_by: Optional[List[str]] = None, group_by: Optional[list[str]] = None,
) -> Page[TRowModel]: ) -> Page[TRowModel]:
if not filters: if not filters:
filters = Filters() filters = Filters()
@@ -298,11 +298,11 @@ class Database(Compat):
async def fetch_page( async def fetch_page(
self, self,
query: str, query: str,
where: Optional[List[str]] = None, where: Optional[list[str]] = None,
values: Optional[List[str]] = None, values: Optional[list[str]] = None,
filters: Optional[Filters] = None, filters: Optional[Filters] = None,
model: Optional[Type[TRowModel]] = None, model: Optional[type[TRowModel]] = None,
group_by: Optional[List[str]] = None, group_by: Optional[list[str]] = None,
) -> Page[TRowModel]: ) -> Page[TRowModel]:
async with self.connect() as conn: async with self.connect() as conn:
return await conn.fetch_page(query, where, values, filters, model, group_by) return await conn.fetch_page(query, where, values, filters, model, group_by)
@@ -370,8 +370,8 @@ class FromRowModel(BaseModel):
class FilterModel(BaseModel): class FilterModel(BaseModel):
__search_fields__: List[str] = [] __search_fields__: list[str] = []
__sort_fields__: Optional[List[str]] = None __sort_fields__: Optional[list[str]] = None
T = TypeVar("T") T = TypeVar("T")
@@ -390,10 +390,10 @@ class Filter(BaseModel, Generic[TFilterModel]):
op: Operator = Operator.EQ op: Operator = Operator.EQ
values: list[Any] values: list[Any]
model: Optional[Type[TFilterModel]] model: Optional[type[TFilterModel]]
@classmethod @classmethod
def parse_query(cls, key: str, raw_values: list[Any], model: Type[TFilterModel]): def parse_query(cls, key: str, raw_values: list[Any], model: type[TFilterModel]):
# Key format: # Key format:
# key[operator] # key[operator]
# e.g. name[eq] # e.g. name[eq]
@@ -443,7 +443,7 @@ class Filters(BaseModel, Generic[TFilterModel]):
the values can be validated. Otherwise, make sure to validate the inputs manually. the values can be validated. Otherwise, make sure to validate the inputs manually.
""" """
filters: List[Filter[TFilterModel]] = [] filters: list[Filter[TFilterModel]] = []
search: Optional[str] = None search: Optional[str] = None
offset: Optional[int] = None offset: Optional[int] = None
@@ -452,7 +452,7 @@ class Filters(BaseModel, Generic[TFilterModel]):
sortby: Optional[str] = None sortby: Optional[str] = None
direction: Optional[Literal["asc", "desc"]] = None direction: Optional[Literal["asc", "desc"]] = None
model: Optional[Type[TFilterModel]] = None model: Optional[type[TFilterModel]] = None
@root_validator(pre=True) @root_validator(pre=True)
def validate_sortby(cls, values): def validate_sortby(cls, values):
@@ -474,7 +474,7 @@ class Filters(BaseModel, Generic[TFilterModel]):
stmt += f"OFFSET {self.offset}" stmt += f"OFFSET {self.offset}"
return stmt return stmt
def where(self, where_stmts: Optional[List[str]] = None) -> str: def where(self, where_stmts: Optional[list[str]] = None) -> str:
if not where_stmts: if not where_stmts:
where_stmts = [] where_stmts = []
if self.filters: if self.filters:
@@ -498,7 +498,7 @@ class Filters(BaseModel, Generic[TFilterModel]):
return f"ORDER BY {self.sortby} {self.direction or 'asc'}" return f"ORDER BY {self.sortby} {self.direction or 'asc'}"
return "" return ""
def values(self, values: Optional[List[str]] = None) -> tuple: def values(self, values: Optional[list[str]] = None) -> tuple:
if not values: if not values:
values = [] values = []
if self.filters: if self.filters:
+80 -167
View File
@@ -17,23 +17,32 @@ from lnbits.core.crud import (
get_user, get_user,
get_wallet_for_key, get_wallet_for_key,
) )
from lnbits.core.models import User, Wallet, WalletType, WalletTypeInfo from lnbits.core.models import KeyType, User, WalletTypeInfo
from lnbits.db import Filter, Filters, TFilterModel from lnbits.db import Filter, Filters, TFilterModel
from lnbits.settings import AuthMethods, settings from lnbits.settings import AuthMethods, settings
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/v1/auth", auto_error=False) oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/v1/auth", auto_error=False)
api_key_header = APIKeyHeader(
name="X-API-KEY",
auto_error=False,
description="Admin or Invoice key for wallet API's",
)
api_key_query = APIKeyQuery(
name="api-key",
auto_error=False,
description="Admin or Invoice key for wallet API's",
)
class KeyChecker(SecurityBase): class KeyChecker(SecurityBase):
def __init__( def __init__(
self, self,
scheme_name: Optional[str] = None,
auto_error: bool = True,
api_key: Optional[str] = None, api_key: Optional[str] = None,
expected_key_type: Optional[KeyType] = None,
): ):
self.scheme_name = scheme_name or self.__class__.__name__ self.auto_error: bool = True
self.auto_error: bool = auto_error self.expected_key_type = expected_key_type
self._key_type: WalletType = WalletType.invoice
self._api_key = api_key self._api_key = api_key
if api_key: if api_key:
openapi_model = APIKey( openapi_model = APIKey(
@@ -49,185 +58,82 @@ class KeyChecker(SecurityBase):
name="X-API-KEY", name="X-API-KEY",
description="Wallet API Key - HEADER", description="Wallet API Key - HEADER",
) )
self.wallet: Optional[Wallet] = None
self.model: APIKey = openapi_model self.model: APIKey = openapi_model
async def __call__(self, request: Request): async def __call__(self, request: Request) -> WalletTypeInfo:
try:
key_value = ( key_value = (
self._api_key self._api_key
if self._api_key if self._api_key
else request.headers.get("X-API-KEY") or request.query_params["api-key"] else request.headers.get("X-API-KEY") or request.query_params.get("api-key")
) )
# FIXME: Find another way to validate the key. A fetch from DB should be
# avoided here. Also, we should not return the wallet here - thats if not key_value:
# silly. Possibly store it in a Redis DB
wallet = await get_wallet_for_key(key_value, self._key_type)
if not wallet:
raise HTTPException(
status_code=HTTPStatus.UNAUTHORIZED,
detail="Invalid key or wallet.",
)
self.wallet = wallet
except KeyError:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, detail="`X-API-KEY` header missing." status_code=HTTPStatus.UNAUTHORIZED,
detail="No Api Key provided.",
) )
wallet = await get_wallet_for_key(key_value)
class WalletInvoiceKeyChecker(KeyChecker): if not wallet:
""" raise HTTPException(
WalletInvoiceKeyChecker will ensure that the provided invoice status_code=HTTPStatus.NOT_FOUND,
wallet key is correct and populate g().wallet with the wallet detail="Wallet not found.",
for the key in `X-API-key`. )
The checker will raise an HTTPException when the key is wrong in some ways. if self.expected_key_type is KeyType.admin and wallet.adminkey != key_value:
""" raise HTTPException(
status_code=HTTPStatus.UNAUTHORIZED,
detail="Invalid adminkey.",
)
def __init__( if (
self, wallet.user != settings.super_user
scheme_name: Optional[str] = None, and wallet.user not in settings.lnbits_admin_users
auto_error: bool = True, and settings.lnbits_admin_extensions
api_key: Optional[str] = None, and request["path"].split("/")[1] in settings.lnbits_admin_extensions
): ):
super().__init__(scheme_name, auto_error, api_key) raise HTTPException(
self._key_type = WalletType.invoice status_code=HTTPStatus.FORBIDDEN,
detail="User not authorized for this extension.",
)
key_type = KeyType.admin if wallet.adminkey == key_value else KeyType.invoice
class WalletAdminKeyChecker(KeyChecker): return WalletTypeInfo(key_type, wallet)
"""
WalletAdminKeyChecker will ensure that the provided admin
wallet key is correct and populate g().wallet with the wallet
for the key in `X-API-key`.
The checker will raise an HTTPException when the key is wrong in some ways.
"""
def __init__(
self,
scheme_name: Optional[str] = None,
auto_error: bool = True,
api_key: Optional[str] = None,
):
super().__init__(scheme_name, auto_error, api_key)
self._key_type = WalletType.admin
api_key_header = APIKeyHeader(
name="X-API-KEY",
auto_error=False,
description="Admin or Invoice key for wallet API's",
)
api_key_query = APIKeyQuery(
name="api-key",
auto_error=False,
description="Admin or Invoice key for wallet API's",
)
async def get_key_type( async def get_key_type(
r: Request, request: Request,
api_key_header: str = Security(api_key_header), api_key_header: str = Security(api_key_header),
api_key_query: str = Security(api_key_query), api_key_query: str = Security(api_key_query),
) -> WalletTypeInfo: ) -> WalletTypeInfo:
token = api_key_header or api_key_query check: KeyChecker = KeyChecker(api_key=api_key_header or api_key_query)
return await check(request)
if not token:
raise HTTPException(
status_code=HTTPStatus.UNAUTHORIZED,
detail="Invoice (or Admin) key required.",
)
for wallet_type, WalletChecker in zip(
[WalletType.admin, WalletType.invoice],
[WalletAdminKeyChecker, WalletInvoiceKeyChecker],
):
try:
checker = WalletChecker(api_key=token)
await checker.__call__(r)
if checker.wallet is None:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Wallet does not exist."
)
wallet = WalletTypeInfo(wallet_type, checker.wallet)
if (
wallet.wallet.user != settings.super_user
and wallet.wallet.user not in settings.lnbits_admin_users
) and (
settings.lnbits_admin_extensions
and r["path"].split("/")[1] in settings.lnbits_admin_extensions
):
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="User not authorized for this extension.",
)
return wallet
except HTTPException as exc:
if exc.status_code == HTTPStatus.BAD_REQUEST:
raise
elif exc.status_code == HTTPStatus.UNAUTHORIZED:
# we pass this in case it is not an invoice key, nor an admin key,
# and then return NOT_FOUND at the end of this block
pass
else:
raise
except Exception:
raise
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Wallet does not exist."
)
async def require_admin_key( async def require_admin_key(
r: Request, request: Request,
api_key_header: str = Security(api_key_header), api_key_header: str = Security(api_key_header),
api_key_query: str = Security(api_key_query), api_key_query: str = Security(api_key_query),
): ) -> WalletTypeInfo:
token = api_key_header or api_key_query check: KeyChecker = KeyChecker(
api_key=api_key_header or api_key_query,
if not token: expected_key_type=KeyType.admin,
raise HTTPException( )
status_code=HTTPStatus.UNAUTHORIZED, return await check(request)
detail="Admin key required.",
)
wallet = await get_key_type(r, token)
if wallet.wallet_type != 0:
# If wallet type is not admin then return the unauthorized status
# This also covers when the user passes an invalid key type
raise HTTPException(
status_code=HTTPStatus.UNAUTHORIZED, detail="Admin key required."
)
else:
return wallet
async def require_invoice_key( async def require_invoice_key(
r: Request, request: Request,
api_key_header: str = Security(api_key_header), api_key_header: str = Security(api_key_header),
api_key_query: str = Security(api_key_query), api_key_query: str = Security(api_key_query),
): ) -> WalletTypeInfo:
token = api_key_header or api_key_query check: KeyChecker = KeyChecker(
api_key=api_key_header or api_key_query,
if not token: expected_key_type=KeyType.invoice,
raise HTTPException( )
status_code=HTTPStatus.UNAUTHORIZED, return await check(request)
detail="Invoice (or Admin) key required.",
)
wallet = await get_key_type(r, token)
if (
wallet.wallet_type != WalletType.admin
and wallet.wallet_type != WalletType.invoice
):
raise HTTPException(
status_code=HTTPStatus.UNAUTHORIZED,
detail="Invoice (or Admin) key required.",
)
else:
return wallet
async def check_access_token( async def check_access_token(
@@ -255,8 +161,15 @@ async def check_user_exists(
user = await get_user(account.id) user = await get_user(account.id)
assert user, "User not found for account." assert user, "User not found for account."
if not user.admin and r["path"].split("/")[1] in settings.lnbits_admin_extensions: if (
raise HTTPException(HTTPStatus.FORBIDDEN, "User not authorized for extension.") user.id != settings.super_user
and user.id not in settings.lnbits_admin_users
and settings.lnbits_admin_extensions
and r["path"].split("/")[1] in settings.lnbits_admin_extensions
):
raise HTTPException(
HTTPStatus.UNAUTHORIZED, "User not authorized for extension."
)
return user return user
@@ -324,10 +237,10 @@ async def _get_account_from_token(access_token):
return await get_account_by_email(str(payload.get("email"))) return await get_account_by_email(str(payload.get("email")))
raise HTTPException(HTTPStatus.UNAUTHORIZED, "Data missing for access token.") raise HTTPException(HTTPStatus.UNAUTHORIZED, "Data missing for access token.")
except ExpiredSignatureError: except ExpiredSignatureError as exc:
raise HTTPException( raise HTTPException(
HTTPStatus.UNAUTHORIZED, "Session expired.", {"token-expired": "true"} HTTPStatus.UNAUTHORIZED, "Session expired.", {"token-expired": "true"}
) ) from exc
except JWTError as e: except JWTError as exc:
logger.debug(e) logger.debug(exc)
raise HTTPException(HTTPStatus.UNAUTHORIZED, "Invalid access token.") raise HTTPException(HTTPStatus.UNAUTHORIZED, "Invalid access token.") from exc
+101
View File
@@ -0,0 +1,101 @@
import sys
import traceback
from http import HTTPStatus
from typing import Optional
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, RedirectResponse, Response
from loguru import logger
from lnbits.core.services import InvoiceError, PaymentError
from .helpers import template_renderer
def register_exception_handlers(app: FastAPI):
register_exception_handler(app)
register_request_validation_exception_handler(app)
register_http_exception_handler(app)
register_payment_error_handler(app)
register_invoice_error_handler(app)
def render_html_error(request: Request, exc: Exception) -> Optional[Response]:
# Only the browser sends "text/html" request
# not fail proof, but everything else get's a JSON response
if (
request.headers
and "accept" in request.headers
and "text/html" in request.headers["accept"]
):
if (
isinstance(exc, HTTPException)
and exc.headers
and "token-expired" in exc.headers
):
response = RedirectResponse("/")
response.delete_cookie("cookie_access_token")
response.delete_cookie("is_lnbits_user_authorized")
response.set_cookie("is_access_token_expired", "true")
return response
return template_renderer().TemplateResponse(
request, "error.html", {"err": f"Error: {exc!s}"}
)
return None
def register_exception_handler(app: FastAPI):
@app.exception_handler(Exception)
async def exception_handler(request: Request, exc: Exception):
etype, _, tb = sys.exc_info()
traceback.print_exception(etype, exc, tb)
logger.error(f"Exception: {exc!s}")
return render_html_error(request, exc) or JSONResponse(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
content={"detail": str(exc)},
)
def register_request_validation_exception_handler(app: FastAPI):
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(
request: Request, exc: RequestValidationError
):
logger.error(f"RequestValidationError: {exc!s}")
return render_html_error(request, exc) or JSONResponse(
status_code=HTTPStatus.BAD_REQUEST,
content={"detail": str(exc)},
)
def register_http_exception_handler(app: FastAPI):
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
logger.error(f"HTTPException {exc.status_code}: {exc.detail}")
return render_html_error(request, exc) or JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail},
)
def register_payment_error_handler(app: FastAPI):
@app.exception_handler(PaymentError)
async def payment_error_handler(request: Request, exc: PaymentError):
logger.error(f"PaymentError: {exc.message}, {exc.status}")
return JSONResponse(
status_code=520,
content={"detail": exc.message, "status": exc.status},
)
def register_invoice_error_handler(app: FastAPI):
@app.exception_handler(InvoiceError)
async def invoice_error_handler(request: Request, exc: InvoiceError):
logger.error(f"InvoiceError: {exc.message}, Status: {exc.status}")
return JSONResponse(
status_code=520,
content={"detail": exc.message, "status": exc.status},
)
+13 -8
View File
@@ -428,9 +428,9 @@ class InstallableExtension(BaseModel):
self._remember_payment_info() self._remember_payment_info()
except Exception as ex: except Exception as exc:
logger.warning(ex) logger.warning(exc)
raise AssertionError("Cannot fetch extension archive file") raise AssertionError("Cannot fetch extension archive file") from exc
archive_hash = file_hash(ext_zip_file) archive_hash = file_hash(ext_zip_file)
if self.installed_release.hash and self.installed_release.hash != archive_hash: if self.installed_release.hash and self.installed_release.hash != archive_hash:
@@ -491,8 +491,9 @@ class InstallableExtension(BaseModel):
settings.lnbits_upgraded_extensions, settings.lnbits_upgraded_extensions,
) )
) )
settings.lnbits_upgraded_extensions = clean_upgraded_exts + [ settings.lnbits_upgraded_extensions = [
f"{self.hash}/{self.id}" *clean_upgraded_exts,
f"{self.hash}/{self.id}",
] ]
def clean_extension_files(self): def clean_extension_files(self):
@@ -559,7 +560,11 @@ class InstallableExtension(BaseModel):
return ext return ext
@classmethod @classmethod
def from_rows(cls, rows: List[Any] = []) -> List["InstallableExtension"]: def from_rows(
cls, rows: Optional[List[Any]] = None
) -> List["InstallableExtension"]:
if rows is None:
rows = []
return [InstallableExtension.from_row(row) for row in rows] return [InstallableExtension.from_row(row) for row in rows]
@classmethod @classmethod
@@ -639,7 +644,7 @@ class InstallableExtension(BaseModel):
extension_list += [ext] extension_list += [ext]
extension_id_list += [e.id] extension_id_list += [e.id]
except Exception as e: except Exception as e:
logger.warning(f"Manifest {url} failed with '{str(e)}'") logger.warning(f"Manifest {url} failed with '{e!s}'")
return extension_list return extension_list
@@ -666,7 +671,7 @@ class InstallableExtension(BaseModel):
extension_releases.append(explicit_release) extension_releases.append(explicit_release)
except Exception as e: except Exception as e:
logger.warning(f"Manifest {url} failed with '{str(e)}'") logger.warning(f"Manifest {url} failed with '{e!s}'")
return extension_releases return extension_releases
+18
View File
@@ -20,6 +20,19 @@ from .db import FilterModel
from .extension_manager import get_valid_extensions from .extension_manager import get_valid_extensions
def get_db_vendor_name():
db_url = settings.lnbits_database_url
return (
"PostgreSQL"
if db_url and db_url.startswith("postgres://")
else (
"CockroachDB"
if db_url and db_url.startswith("cockroachdb://")
else "SQLite"
)
)
def urlsafe_short_hash() -> str: def urlsafe_short_hash() -> str:
return shortuuid.uuid() return shortuuid.uuid()
@@ -58,6 +71,11 @@ def template_renderer(additional_folders: Optional[List] = None) -> Jinja2Templa
t.env.globals["LNBITS_DENOMINATION"] = settings.lnbits_denomination t.env.globals["LNBITS_DENOMINATION"] = settings.lnbits_denomination
t.env.globals["SITE_TAGLINE"] = settings.lnbits_site_tagline t.env.globals["SITE_TAGLINE"] = settings.lnbits_site_tagline
t.env.globals["SITE_DESCRIPTION"] = settings.lnbits_site_description t.env.globals["SITE_DESCRIPTION"] = settings.lnbits_site_description
t.env.globals["LNBITS_SHOW_HOME_PAGE_ELEMENTS"] = (
settings.LNBITS_SHOW_HOME_PAGE_ELEMENTS
)
t.env.globals["LNBITS_CUSTOM_BADGE"] = settings.lnbits_custom_badge
t.env.globals["LNBITS_CUSTOM_BADGE_COLOR"] = settings.lnbits_custom_badge_color
t.env.globals["LNBITS_THEME_OPTIONS"] = settings.lnbits_theme_options t.env.globals["LNBITS_THEME_OPTIONS"] = settings.lnbits_theme_options
t.env.globals["LNBITS_QR_LOGO"] = settings.lnbits_qr_logo t.env.globals["LNBITS_QR_LOGO"] = settings.lnbits_qr_logo
t.env.globals["LNBITS_VERSION"] = settings.version t.env.globals["LNBITS_VERSION"] = settings.version
+2 -2
View File
@@ -29,7 +29,7 @@ class InstalledExtensionMiddleware:
await self.app(scope, receive, send) await self.app(scope, receive, send)
return return
top_path, *rest = [p for p in full_path.split("/") if p] top_path, *rest = (p for p in full_path.split("/") if p)
headers = scope.get("headers", []) headers = scope.get("headers", [])
# block path for all users if the extension is disabled # block path for all users if the extension is disabled
@@ -179,7 +179,7 @@ class ExtensionsRedirectMiddleware:
req_tail_path = req_path.split("/")[len(from_path) :] req_tail_path = req_path.split("/")[len(from_path) :]
elements = [ elements = [
e for e in ([redirect["ext_id"]] + redirect_to + req_tail_path) if e != "" e for e in ([redirect["ext_id"], *redirect_to, *req_tail_path]) if e != ""
] ]
return "/" + "/".join(elements) return "/" + "/".join(elements)
+2 -2
View File
@@ -2,7 +2,7 @@ from __future__ import annotations
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from enum import Enum from enum import Enum
from typing import TYPE_CHECKING, List, Optional from typing import TYPE_CHECKING, Optional
from pydantic import BaseModel from pydantic import BaseModel
@@ -212,7 +212,7 @@ class Node(ABC):
pass pass
@abstractmethod @abstractmethod
async def get_channels(self) -> List[NodeChannel]: async def get_channels(self) -> list[NodeChannel]:
pass pass
@abstractmethod @abstractmethod
+26 -23
View File
@@ -2,7 +2,7 @@ from __future__ import annotations
import asyncio import asyncio
from http import HTTPStatus from http import HTTPStatus
from typing import TYPE_CHECKING, List, Optional from typing import TYPE_CHECKING, Optional
from fastapi import HTTPException from fastapi import HTTPException
@@ -44,11 +44,12 @@ def catch_rpc_errors(f):
async def wrapper(*args, **kwargs): async def wrapper(*args, **kwargs):
try: try:
return await f(*args, **kwargs) return await f(*args, **kwargs)
except RpcError as e: except RpcError as exc:
if e.error["code"] == -32602: msg = exc.error["message"]
raise HTTPException(status_code=400, detail=e.error["message"]) if exc.error["code"] == -32602:
raise HTTPException(status_code=400, detail=msg) from exc
else: else:
raise HTTPException(status_code=500, detail=e.error["message"]) raise HTTPException(status_code=500, detail=msg) from exc
return wrapper return wrapper
@@ -66,9 +67,11 @@ class CoreLightningNode(Node):
# https://docs.corelightning.org/reference/lightning-connect # https://docs.corelightning.org/reference/lightning-connect
try: try:
await self.ln_rpc("connect", uri) await self.ln_rpc("connect", uri)
except RpcError as e: except RpcError as exc:
if e.error["code"] == 400: if exc.error["code"] == 400:
raise HTTPException(HTTPStatus.BAD_REQUEST, detail=e.error["message"]) raise HTTPException(
HTTPStatus.BAD_REQUEST, detail=exc.error["message"]
) from exc
else: else:
raise raise
@@ -76,12 +79,12 @@ class CoreLightningNode(Node):
async def disconnect_peer(self, peer_id: str): async def disconnect_peer(self, peer_id: str):
try: try:
await self.ln_rpc("disconnect", peer_id) await self.ln_rpc("disconnect", peer_id)
except RpcError as e: except RpcError as exc:
if e.error["code"] == -1: if exc.error["code"] == -1:
raise HTTPException( raise HTTPException(
HTTPStatus.BAD_REQUEST, HTTPStatus.BAD_REQUEST,
detail=e.error["message"], detail=exc.error["message"],
) ) from exc
else: else:
raise raise
@@ -105,14 +108,14 @@ class CoreLightningNode(Node):
funding_txid=result["txid"], funding_txid=result["txid"],
output_index=result["outnum"], output_index=result["outnum"],
) )
except RpcError as e: except RpcError as exc:
message = e.error["message"] message = exc.error["message"]
if "amount: should be a satoshi amount" in message: if "amount: should be a satoshi amount" in message:
raise HTTPException( raise HTTPException(
HTTPStatus.BAD_REQUEST, HTTPStatus.BAD_REQUEST,
detail="The amount is not a valid satoshi amount.", detail="The amount is not a valid satoshi amount.",
) ) from exc
if "Unknown peer" in message: if "Unknown peer" in message:
raise HTTPException( raise HTTPException(
@@ -121,7 +124,7 @@ class CoreLightningNode(Node):
"We where able to connect to the peer but CLN " "We where able to connect to the peer but CLN "
"can't find it when opening a channel." "can't find it when opening a channel."
), ),
) ) from exc
if "Owning subdaemon openingd died" in message: if "Owning subdaemon openingd died" in message:
# https://github.com/ElementsProject/lightning/issues/2798#issuecomment-511205719 # https://github.com/ElementsProject/lightning/issues/2798#issuecomment-511205719
@@ -131,14 +134,14 @@ class CoreLightningNode(Node):
"Likely the peer didn't like our channel opening " "Likely the peer didn't like our channel opening "
"proposal and disconnected from us." "proposal and disconnected from us."
), ),
) ) from exc
if ( if (
"Number of pending channels exceed maximum" in message "Number of pending channels exceed maximum" in message
or "exceeds maximum chan size of 10 BTC" in message or "exceeds maximum chan size of 10 BTC" in message
or "Could not afford" in message or "Could not afford" in message
): ):
raise HTTPException(HTTPStatus.BAD_REQUEST, detail=message) raise HTTPException(HTTPStatus.BAD_REQUEST, detail=message) from exc
raise raise
@catch_rpc_errors @catch_rpc_errors
@@ -152,13 +155,13 @@ class CoreLightningNode(Node):
raise HTTPException(status_code=400, detail="Short id required") raise HTTPException(status_code=400, detail="Short id required")
try: try:
await self.ln_rpc("close", short_id) await self.ln_rpc("close", short_id)
except RpcError as e: except RpcError as exc:
message = e.error["message"] message = exc.error["message"]
if ( if (
"Short channel ID not active:" in message "Short channel ID not active:" in message
or "Short channel ID not found" in message or "Short channel ID not found" in message
): ):
raise HTTPException(HTTPStatus.BAD_REQUEST, detail=message) raise HTTPException(HTTPStatus.BAD_REQUEST, detail=message) from exc
else: else:
raise raise
@@ -168,7 +171,7 @@ class CoreLightningNode(Node):
return info["id"] return info["id"]
@catch_rpc_errors @catch_rpc_errors
async def get_peer_ids(self) -> List[str]: async def get_peer_ids(self) -> list[str]:
peers = await self.ln_rpc("listpeers") peers = await self.ln_rpc("listpeers")
return [p["id"] for p in peers["peers"] if p["connected"]] return [p["id"] for p in peers["peers"] if p["connected"]]
@@ -194,7 +197,7 @@ class CoreLightningNode(Node):
return NodePeerInfo(id=node["nodeid"]) return NodePeerInfo(id=node["nodeid"])
@catch_rpc_errors @catch_rpc_errors
async def get_channels(self) -> List[NodeChannel]: async def get_channels(self) -> list[NodeChannel]:
funds = await self.ln_rpc("listfunds") funds = await self.ln_rpc("listfunds")
nodes = await self.ln_rpc("listnodes") nodes = await self.ln_rpc("listnodes")
nodes_by_id = {n["nodeid"]: n for n in nodes["nodes"]} nodes_by_id = {n["nodeid"]: n for n in nodes["nodes"]}
+13 -11
View File
@@ -4,7 +4,7 @@ import asyncio
import base64 import base64
import json import json
from http import HTTPStatus from http import HTTPStatus
from typing import TYPE_CHECKING, List, Optional from typing import TYPE_CHECKING, Optional
from fastapi import HTTPException from fastapi import HTTPException
from httpx import HTTPStatusError from httpx import HTTPStatusError
@@ -60,11 +60,13 @@ class LndRestNode(Node):
) )
try: try:
response.raise_for_status() response.raise_for_status()
except HTTPStatusError as e: except HTTPStatusError as exc:
json = e.response.json() json = exc.response.json()
if json: if json:
error = json.get("error") or json error = json.get("error") or json
raise HTTPException(e.response.status_code, detail=error.get("message")) raise HTTPException(
exc.response.status_code, detail=error.get("message")
) from exc
return response.json() return response.json()
def get(self, path: str, **kwargs): def get(self, path: str, **kwargs):
@@ -81,8 +83,8 @@ class LndRestNode(Node):
async def connect_peer(self, uri: str): async def connect_peer(self, uri: str):
try: try:
pubkey, host = uri.split("@") pubkey, host = uri.split("@")
except ValueError: except ValueError as exc:
raise HTTPException(400, detail="Invalid peer URI") raise HTTPException(400, detail="Invalid peer URI") from exc
await self.request( await self.request(
"POST", "POST",
"/v1/peers", "/v1/peers",
@@ -96,11 +98,11 @@ class LndRestNode(Node):
async def disconnect_peer(self, peer_id: str): async def disconnect_peer(self, peer_id: str):
try: try:
await self.request("DELETE", "/v1/peers/" + peer_id) await self.request("DELETE", "/v1/peers/" + peer_id)
except HTTPException as e: except HTTPException as exc:
if "unable to disconnect" in e.detail: if "unable to disconnect" in exc.detail:
raise HTTPException( raise HTTPException(
HTTPStatus.BAD_REQUEST, detail="Peer is not connected" HTTPStatus.BAD_REQUEST, detail="Peer is not connected"
) ) from exc
raise raise
async def _get_peer_info(self, peer_id: str) -> NodePeerInfo: async def _get_peer_info(self, peer_id: str) -> NodePeerInfo:
@@ -174,9 +176,9 @@ class LndRestNode(Node):
status_code=HTTPStatus.BAD_REQUEST, detail="Channel point required" status_code=HTTPStatus.BAD_REQUEST, detail="Channel point required"
) )
asyncio.create_task(self._close_channel(point, force)) asyncio.create_task(self._close_channel(point, force)) # noqa: RUF006
async def get_channels(self) -> List[NodeChannel]: async def get_channels(self) -> list[NodeChannel]:
normal, pending, closed = await asyncio.gather( normal, pending, closed = await asyncio.gather(
self.get("/v1/channels"), self.get("/v1/channels"),
self.get("/v1/channels/pending"), self.get("/v1/channels/pending"),
+1
View File
@@ -0,0 +1 @@
# Marker file for PEP 561
+5 -18
View File
@@ -24,14 +24,16 @@ from lnbits.settings import set_cli_settings, settings
) )
@click.option("--ssl-keyfile", default=None, help="Path to SSL keyfile") @click.option("--ssl-keyfile", default=None, help="Path to SSL keyfile")
@click.option("--ssl-certfile", default=None, help="Path to SSL certificate") @click.option("--ssl-certfile", default=None, help="Path to SSL certificate")
@click.pass_context @click.option(
"--reload", is_flag=True, default=False, help="Enable auto-reload for development"
)
def main( def main(
ctx,
port: int, port: int,
host: str, host: str,
forwarded_allow_ips: str, forwarded_allow_ips: str,
ssl_keyfile: str, ssl_keyfile: str,
ssl_certfile: str, ssl_certfile: str,
reload: bool,
): ):
"""Launched with `poetry run lnbits` at root level""" """Launched with `poetry run lnbits` at root level"""
@@ -46,21 +48,6 @@ def main(
set_cli_settings(host=host, port=port, forwarded_allow_ips=forwarded_allow_ips) set_cli_settings(host=host, port=port, forwarded_allow_ips=forwarded_allow_ips)
# this beautiful beast parses all command line arguments and
# passes them to the uvicorn server
d = {}
for a in ctx.args:
item = a.split("=")
if len(item) > 1: # argument like --key=value
print(a, item)
d[item[0].strip("--").replace("-", "_")] = (
int(item[1]) # need to convert to int if it's a number
if item[1].isdigit()
else item[1]
)
else:
d[a.strip("--")] = True # argument like --key
while True: while True:
config = uvicorn.Config( config = uvicorn.Config(
"lnbits.__main__:app", "lnbits.__main__:app",
@@ -70,7 +57,7 @@ def main(
forwarded_allow_ips=forwarded_allow_ips, forwarded_allow_ips=forwarded_allow_ips,
ssl_keyfile=ssl_keyfile, ssl_keyfile=ssl_keyfile,
ssl_certfile=ssl_certfile, ssl_certfile=ssl_certfile,
**d reload=reload or False,
) )
server = uvicorn.Server(config=config) server = uvicorn.Server(config=config)
+54 -34
View File
@@ -9,7 +9,7 @@ from hashlib import sha256
from os import path from os import path
from sqlite3 import Row from sqlite3 import Row
from time import time from time import time
from typing import Any, List, Optional from typing import Any, Optional
import httpx import httpx
from loguru import logger from loguru import logger
@@ -36,8 +36,8 @@ class LNbitsSettings(BaseModel):
class UsersSettings(LNbitsSettings): class UsersSettings(LNbitsSettings):
lnbits_admin_users: List[str] = Field(default=[]) lnbits_admin_users: list[str] = Field(default=[])
lnbits_allowed_users: List[str] = Field(default=[]) lnbits_allowed_users: list[str] = Field(default=[])
lnbits_allow_new_accounts: bool = Field(default=True) lnbits_allow_new_accounts: bool = Field(default=True)
@property @property
@@ -46,9 +46,9 @@ class UsersSettings(LNbitsSettings):
class ExtensionsSettings(LNbitsSettings): class ExtensionsSettings(LNbitsSettings):
lnbits_admin_extensions: List[str] = Field(default=[]) lnbits_admin_extensions: list[str] = Field(default=[])
lnbits_extensions_deactivate_all: bool = Field(default=False) lnbits_extensions_deactivate_all: bool = Field(default=False)
lnbits_extensions_manifests: List[str] = Field( lnbits_extensions_manifests: list[str] = Field(
default=[ default=[
"https://raw.githubusercontent.com/lnbits/lnbits-extensions/main/extensions.json" "https://raw.githubusercontent.com/lnbits/lnbits-extensions/main/extensions.json"
] ]
@@ -56,18 +56,18 @@ class ExtensionsSettings(LNbitsSettings):
class ExtensionsInstallSettings(LNbitsSettings): class ExtensionsInstallSettings(LNbitsSettings):
lnbits_extensions_default_install: List[str] = Field(default=[]) lnbits_extensions_default_install: list[str] = Field(default=[])
# required due to GitHUb rate-limit # required due to GitHUb rate-limit
lnbits_ext_github_token: str = Field(default="") lnbits_ext_github_token: str = Field(default="")
class InstalledExtensionsSettings(LNbitsSettings): class InstalledExtensionsSettings(LNbitsSettings):
# installed extensions that have been deactivated # installed extensions that have been deactivated
lnbits_deactivated_extensions: List[str] = Field(default=[]) lnbits_deactivated_extensions: list[str] = Field(default=[])
# upgraded extensions that require API redirects # upgraded extensions that require API redirects
lnbits_upgraded_extensions: List[str] = Field(default=[]) lnbits_upgraded_extensions: list[str] = Field(default=[])
# list of redirects that extensions want to perform # list of redirects that extensions want to perform
lnbits_extensions_redirects: List[Any] = Field(default=[]) lnbits_extensions_redirects: list[Any] = Field(default=[])
def extension_upgrade_path(self, ext_id: str) -> Optional[str]: def extension_upgrade_path(self, ext_id: str) -> Optional[str]:
return next( return next(
@@ -83,9 +83,14 @@ class InstalledExtensionsSettings(LNbitsSettings):
class ThemesSettings(LNbitsSettings): class ThemesSettings(LNbitsSettings):
lnbits_site_title: str = Field(default="LNbits") lnbits_site_title: str = Field(default="LNbits")
lnbits_site_tagline: str = Field(default="free and open-source lightning wallet") lnbits_site_tagline: str = Field(default="free and open-source lightning wallet")
lnbits_site_description: str = Field(default=None) lnbits_site_description: Optional[str] = Field(
default="The world's most powerful suite of bitcoin tools."
)
LNBITS_SHOW_HOME_PAGE_ELEMENTS: bool = Field(default=True)
lnbits_default_wallet_name: str = Field(default="LNbits wallet") lnbits_default_wallet_name: str = Field(default="LNbits wallet")
lnbits_theme_options: List[str] = Field( lnbits_custom_badge: str = Field(default=None)
lnbits_custom_badge_color: str = Field(default="warning")
lnbits_theme_options: list[str] = Field(
default=[ default=[
"classic", "classic",
"freedom", "freedom",
@@ -99,10 +104,10 @@ class ThemesSettings(LNbitsSettings):
lnbits_custom_logo: str = Field(default=None) lnbits_custom_logo: str = Field(default=None)
lnbits_ad_space_title: str = Field(default="Supported by") lnbits_ad_space_title: str = Field(default="Supported by")
lnbits_ad_space: str = Field( lnbits_ad_space: str = Field(
default="https://shop.lnbits.com/;/static/images/lnbits-shop-light.png;/static/images/lnbits-shop-dark.png" default="https://shop.lnbits.com/;/static/images/bitcoin-shop-banner.png;/static/images/bitcoin-shop-banner.png,https://affil.trezor.io/aff_c?offer_id=169&aff_id=33845;/static/images/bitcoin-hardware-wallet.png;/static/images/bitcoin-hardware-wallet.png,https://opensats.org/;/static/images/open-sats.png;/static/images/open-sats.png"
) # sneaky sneaky ) # sneaky sneaky
lnbits_ad_space_enabled: bool = Field(default=False) lnbits_ad_space_enabled: bool = Field(default=False)
lnbits_allowed_currencies: List[str] = Field(default=[]) lnbits_allowed_currencies: list[str] = Field(default=[])
lnbits_default_accounting_currency: Optional[str] = Field(default=None) lnbits_default_accounting_currency: Optional[str] = Field(default=None)
lnbits_qr_logo: str = Field(default="/static/images/logos/lnbits.png") lnbits_qr_logo: str = Field(default="/static/images/logos/lnbits.png")
@@ -122,8 +127,8 @@ class OpsSettings(LNbitsSettings):
class SecuritySettings(LNbitsSettings): class SecuritySettings(LNbitsSettings):
lnbits_rate_limit_no: str = Field(default="200") lnbits_rate_limit_no: str = Field(default="200")
lnbits_rate_limit_unit: str = Field(default="minute") lnbits_rate_limit_unit: str = Field(default="minute")
lnbits_allowed_ips: List[str] = Field(default=[]) lnbits_allowed_ips: list[str] = Field(default=[])
lnbits_blocked_ips: List[str] = Field(default=[]) lnbits_blocked_ips: list[str] = Field(default=[])
lnbits_notifications: bool = Field(default=False) lnbits_notifications: bool = Field(default=False)
lnbits_killswitch: bool = Field(default=False) lnbits_killswitch: bool = Field(default=False)
lnbits_killswitch_interval: int = Field(default=60) lnbits_killswitch_interval: int = Field(default=60)
@@ -152,7 +157,7 @@ class FakeWalletFundingSource(LNbitsSettings):
class LNbitsFundingSource(LNbitsSettings): class LNbitsFundingSource(LNbitsSettings):
lnbits_endpoint: str = Field(default="https://legend.lnbits.com") lnbits_endpoint: str = Field(default="https://demo.lnbits.com")
lnbits_key: Optional[str] = Field(default=None) lnbits_key: Optional[str] = Field(default=None)
lnbits_admin_key: Optional[str] = Field(default=None) lnbits_admin_key: Optional[str] = Field(default=None)
lnbits_invoice_key: Optional[str] = Field(default=None) lnbits_invoice_key: Optional[str] = Field(default=None)
@@ -164,6 +169,7 @@ class ClicheFundingSource(LNbitsSettings):
class CoreLightningFundingSource(LNbitsSettings): class CoreLightningFundingSource(LNbitsSettings):
corelightning_rpc: Optional[str] = Field(default=None) corelightning_rpc: Optional[str] = Field(default=None)
corelightning_pay_command: str = Field(default="pay")
clightning_rpc: Optional[str] = Field(default=None) clightning_rpc: Optional[str] = Field(default=None)
@@ -213,6 +219,11 @@ class ZBDFundingSource(LNbitsSettings):
zbd_api_key: Optional[str] = Field(default=None) zbd_api_key: Optional[str] = Field(default=None)
class PhoenixdFundingSource(LNbitsSettings):
phoenixd_api_endpoint: Optional[str] = Field(default="http://localhost:9740/")
phoenixd_api_password: Optional[str] = Field(default=None)
class AlbyFundingSource(LNbitsSettings): class AlbyFundingSource(LNbitsSettings):
alby_api_endpoint: Optional[str] = Field(default="https://api.getalby.com/") alby_api_endpoint: Optional[str] = Field(default="https://api.getalby.com/")
alby_access_token: Optional[str] = Field(default=None) alby_access_token: Optional[str] = Field(default=None)
@@ -253,6 +264,7 @@ class FundingSourcesSettings(
LnPayFundingSource, LnPayFundingSource,
AlbyFundingSource, AlbyFundingSource,
ZBDFundingSource, ZBDFundingSource,
PhoenixdFundingSource,
OpenNodeFundingSource, OpenNodeFundingSource,
SparkFundingSource, SparkFundingSource,
LnTipsFundingSource, LnTipsFundingSource,
@@ -286,7 +298,7 @@ class AuthMethods(Enum):
class AuthSettings(LNbitsSettings): class AuthSettings(LNbitsSettings):
auth_token_expire_minutes: int = Field(default=525600) auth_token_expire_minutes: int = Field(default=525600)
auth_all_methods = [a.value for a in AuthMethods] auth_all_methods = [a.value for a in AuthMethods]
auth_allowed_methods: List[str] = Field( auth_allowed_methods: list[str] = Field(
default=[ default=[
AuthMethods.user_id_only.value, AuthMethods.user_id_only.value,
AuthMethods.username_and_password.value, AuthMethods.username_and_password.value,
@@ -377,6 +389,7 @@ class EnvSettings(LNbitsSettings):
log_retention: str = Field(default="3 months") log_retention: str = Field(default="3 months")
server_startup_time: int = Field(default=time()) server_startup_time: int = Field(default=time())
cleanup_wallets_days: int = Field(default=90) cleanup_wallets_days: int = Field(default=90)
funding_source_max_retries: int = Field(default=4)
@property @property
def has_default_extension_path(self) -> bool: def has_default_extension_path(self) -> bool:
@@ -395,21 +408,22 @@ class PersistenceSettings(LNbitsSettings):
class SuperUserSettings(LNbitsSettings): class SuperUserSettings(LNbitsSettings):
lnbits_allowed_funding_sources: List[str] = Field( lnbits_allowed_funding_sources: list[str] = Field(
default=[ default=[
"VoidWallet",
"FakeWallet",
"CoreLightningWallet",
"CoreLightningRestWallet",
"LndRestWallet",
"EclairWallet",
"LndWallet",
"LnTipsWallet",
"LNPayWallet",
"AlbyWallet", "AlbyWallet",
"ZBDWallet", "FakeWallet",
"CoreLightningRestWallet",
"CoreLightningWallet",
"EclairWallet",
"LNbitsWallet", "LNbitsWallet",
"LndRestWallet",
"LNPayWallet",
"LnTipsWallet",
"LndWallet",
"OpenNodeWallet", "OpenNodeWallet",
"PhoenixdWallet",
"VoidWallet",
"ZBDWallet",
] ]
) )
@@ -422,6 +436,12 @@ class TransientSettings(InstalledExtensionsSettings):
# - are cleared on server restart # - are cleared on server restart
first_install: bool = Field(default=False) first_install: bool = Field(default=False)
# Indicates that the server should continue to run.
# When set to false it indicates that the shutdown procedure is ongoing.
# If false no new tasks, threads, etc should be started.
# Long running while loops should use this flag instead of `while True:`
lnbits_running: bool = Field(default=True)
@classmethod @classmethod
def readonly_fields(cls): def readonly_fields(cls):
return [f for f in inspect.signature(cls).parameters if not f.startswith("_")] return [f for f in inspect.signature(cls).parameters if not f.startswith("_")]
@@ -451,7 +471,7 @@ class ReadOnlySettings(
class Settings(EditableSettings, ReadOnlySettings, TransientSettings, BaseSettings): class Settings(EditableSettings, ReadOnlySettings, TransientSettings, BaseSettings):
@classmethod @classmethod
def from_row(cls, row: Row) -> "Settings": def from_row(cls, row: Row) -> Settings:
data = dict(row) data = dict(row)
return cls(**data) return cls(**data)
@@ -476,7 +496,7 @@ class SuperSettings(EditableSettings):
class AdminSettings(EditableSettings): class AdminSettings(EditableSettings):
is_super_user: bool is_super_user: bool
lnbits_allowed_funding_sources: Optional[List[str]] lnbits_allowed_funding_sources: Optional[list[str]]
def set_cli_settings(**kwargs): def set_cli_settings(**kwargs):
@@ -505,7 +525,7 @@ def send_admin_user_to_saas():
except Exception as e: except Exception as e:
logger.error( logger.error(
"error sending super_user to saas:" "error sending super_user to saas:"
f" {settings.lnbits_saas_callback}. Error: {str(e)}" f" {settings.lnbits_saas_callback}. Error: {e!s}"
) )
@@ -531,10 +551,10 @@ if not settings.lnbits_admin_ui:
logger.debug(f"{key}: {value}") logger.debug(f"{key}: {value}")
def get_wallet_class(): def get_funding_source():
""" """
Backwards compatibility Backwards compatibility
""" """
from lnbits.wallets import get_wallet_class from lnbits.wallets import get_funding_source
return get_wallet_class() return get_funding_source()
+10 -10
View File
File diff suppressed because one or more lines are too long
+9 -1
View File
@@ -99,6 +99,7 @@ window.localisation.br = {
'Este é um código QR de retirada do LNURL para sugar tudo desta carteira. Não compartilhe com ninguém. É compatível com balanceCheck e balanceNotify para que sua carteira possa continuar retirando os fundos continuamente daqui após a primeira retirada.', 'Este é um código QR de retirada do LNURL para sugar tudo desta carteira. Não compartilhe com ninguém. É compatível com balanceCheck e balanceNotify para que sua carteira possa continuar retirando os fundos continuamente daqui após a primeira retirada.',
i_understand: 'Eu entendo', i_understand: 'Eu entendo',
copy_wallet_url: 'Copiar URL da carteira', copy_wallet_url: 'Copiar URL da carteira',
disclaimer_dialog_title: 'Importante!',
disclaimer_dialog: disclaimer_dialog:
'Funcionalidade de login a ser lançada em uma atualização futura, por enquanto, certifique-se de marcar esta página para acesso futuro à sua carteira! Este serviço está em BETA, e não nos responsabilizamos por pessoas que perderem o acesso aos fundos.', 'Funcionalidade de login a ser lançada em uma atualização futura, por enquanto, certifique-se de marcar esta página para acesso futuro à sua carteira! Este serviço está em BETA, e não nos responsabilizamos por pessoas que perderem o acesso aos fundos.',
no_transactions: 'Ainda não foram feitas transações', no_transactions: 'Ainda não foram feitas transações',
@@ -241,5 +242,12 @@ window.localisation.br = {
logout: 'Sair', logout: 'Sair',
look_and_feel: 'Aparência', look_and_feel: 'Aparência',
language: 'Idioma', language: 'Idioma',
color_scheme: 'Esquema de Cores' color_scheme: 'Esquema de Cores',
extension_cost: 'Este lançamento requer um pagamento mínimo de %{cost} sats.',
extension_paid_sats: 'Você já pagou %{paid_sats} sats.',
release_details_error: 'Não é possível obter os detalhes da versão.',
pay_from_wallet: 'Pagar com a Carteira',
show_qr: 'Exibir QR',
retry_install: 'Repetir Instalação',
new_payment: 'Efetuar Novo Pagamento'
} }
+9 -1
View File
@@ -95,6 +95,7 @@ window.localisation.cn = {
'这是一个 LNURL-取款的二维码,用于从该钱包中提取全部资金。请不要与他人分享。它与 balanceCheck 和 balanceNotify 兼容,因此在第一次取款后,您的钱包还可能会持续从这里提取资金', '这是一个 LNURL-取款的二维码,用于从该钱包中提取全部资金。请不要与他人分享。它与 balanceCheck 和 balanceNotify 兼容,因此在第一次取款后,您的钱包还可能会持续从这里提取资金',
i_understand: '我明白', i_understand: '我明白',
copy_wallet_url: '复制钱包URL', copy_wallet_url: '复制钱包URL',
disclaimer_dialog_title: '重要!',
disclaimer_dialog: disclaimer_dialog:
'登录功能将在以后的更新中发布,请将此页面加为书签,以便将来访问您的钱包!此服务处于测试阶段,我们不对资金的丢失承担任何责任。', '登录功能将在以后的更新中发布,请将此页面加为书签,以便将来访问您的钱包!此服务处于测试阶段,我们不对资金的丢失承担任何责任。',
no_transactions: '尚未进行任何交易', no_transactions: '尚未进行任何交易',
@@ -229,5 +230,12 @@ window.localisation.cn = {
logout: '注销', logout: '注销',
look_and_feel: '外观和感觉', look_and_feel: '外观和感觉',
language: '语言', language: '语言',
color_scheme: '配色方案' color_scheme: '配色方案',
extension_cost: '此版本需要支付最低 %{cost} sats。',
extension_paid_sats: '您已经支付了%{paid_sats} sats。',
release_details_error: '无法获取发布详情。',
pay_from_wallet: '从钱包支付',
show_qr: '显示QR码',
retry_install: '重试安装',
new_payment: '创建新支付'
} }
+9 -1
View File
@@ -99,6 +99,7 @@ window.localisation.cs = {
'Toto je LNURL-withdraw QR kód pro vyčerpání všeho z této peněženky. Nesdílejte s nikým. Je kompatibilní s balanceCheck a balanceNotify, takže vaše peněženka může kontinuálně čerpat prostředky odsud po prvním výběru.', 'Toto je LNURL-withdraw QR kód pro vyčerpání všeho z této peněženky. Nesdílejte s nikým. Je kompatibilní s balanceCheck a balanceNotify, takže vaše peněženka může kontinuálně čerpat prostředky odsud po prvním výběru.',
i_understand: 'Rozumím', i_understand: 'Rozumím',
copy_wallet_url: 'Kopírovat URL peněženky', copy_wallet_url: 'Kopírovat URL peněženky',
disclaimer_dialog_title: 'Důležité!',
disclaimer_dialog: disclaimer_dialog:
'Funkcionalita přihlášení bude vydána v budoucí aktualizaci, zatím si ujistěte, že jste si tuto stránku uložili do záložek pro budoucí přístup k vaší peněžence! Tato služba je v BETA verzi a nepřebíráme žádnou zodpovědnost za ztrátu přístupu k prostředkům.', 'Funkcionalita přihlášení bude vydána v budoucí aktualizaci, zatím si ujistěte, že jste si tuto stránku uložili do záložek pro budoucí přístup k vaší peněžence! Tato služba je v BETA verzi a nepřebíráme žádnou zodpovědnost za ztrátu přístupu k prostředkům.',
no_transactions: 'Zatím žádné transakce', no_transactions: 'Zatím žádné transakce',
@@ -238,5 +239,12 @@ window.localisation.cs = {
logout: 'Odhlásit se', logout: 'Odhlásit se',
look_and_feel: 'Vzhled a chování', look_and_feel: 'Vzhled a chování',
language: 'Jazyk', language: 'Jazyk',
color_scheme: 'Barevné schéma' color_scheme: 'Barevné schéma',
extension_cost: 'Toto vydání vyžaduje minimální platbu %{cost} satoshi.',
extension_paid_sats: 'Již jste zaplatili %{paid_sats} sats.',
release_details_error: 'Nelze získat podrobnosti o vydání.',
pay_from_wallet: 'Platit z peněženky',
show_qr: 'Zobrazit QR',
retry_install: 'Zkusit znovu nainstalovat',
new_payment: 'Vytvořit novou platbu'
} }
+10 -1
View File
@@ -102,6 +102,7 @@ window.localisation.de = {
'LNURL-withdraw QR-Code, der das Abziehen aller Geldmittel aus dieser Wallet erlaubt. Teile ihn mit niemandem! Kompatibel mit balanceCheck und balanceNotify, so dass dein Wallet die Sats nach dem ersten Abzug kontinuierlich von hier abziehen kann.', 'LNURL-withdraw QR-Code, der das Abziehen aller Geldmittel aus dieser Wallet erlaubt. Teile ihn mit niemandem! Kompatibel mit balanceCheck und balanceNotify, so dass dein Wallet die Sats nach dem ersten Abzug kontinuierlich von hier abziehen kann.',
i_understand: 'Ich verstehe', i_understand: 'Ich verstehe',
copy_wallet_url: 'Wallet-URL kopieren', copy_wallet_url: 'Wallet-URL kopieren',
disclaimer_dialog_title: 'Wichtig!',
disclaimer_dialog: disclaimer_dialog:
'Login-Funktionalität wird in einem zukünftigen Update veröffentlicht. Bis dahin ist die Speicherung der Wallet-URL als Lesezeichen absolut notwendig, um Zugriff auf die Wallet zu erhalten! Dieser Service ist in BETA und wir übernehmen keine Verantwortung für Verluste durch verlorene Zugriffe.', 'Login-Funktionalität wird in einem zukünftigen Update veröffentlicht. Bis dahin ist die Speicherung der Wallet-URL als Lesezeichen absolut notwendig, um Zugriff auf die Wallet zu erhalten! Dieser Service ist in BETA und wir übernehmen keine Verantwortung für Verluste durch verlorene Zugriffe.',
no_transactions: 'Keine Transaktionen', no_transactions: 'Keine Transaktionen',
@@ -245,5 +246,13 @@ window.localisation.de = {
logout: 'Abmelden', logout: 'Abmelden',
look_and_feel: 'Aussehen und Verhalten', look_and_feel: 'Aussehen und Verhalten',
language: 'Sprache', language: 'Sprache',
color_scheme: 'Farbschema' color_scheme: 'Farbschema',
extension_cost:
'Diese Version erfordert eine Zahlung von mindestens %{cost} Sats.',
extension_paid_sats: 'Sie haben bereits %{paid_sats} Sats bezahlt.',
release_details_error: 'Kann die Details zur Veröffentlichung nicht abrufen.',
pay_from_wallet: 'Zahlen aus dem Geldbeutel',
show_qr: 'QR anzeigen',
retry_install: 'Installieren erneut versuchen',
new_payment: 'Neue Zahlung vornehmen'
} }
+8 -6
View File
@@ -9,6 +9,8 @@ window.localisation.en = {
transactions: 'Transactions', transactions: 'Transactions',
dashboard: 'Dashboard', dashboard: 'Dashboard',
node: 'Node', node: 'Node',
export_users: 'Export Users',
no_users: 'No users found',
total_capacity: 'Total Capacity', total_capacity: 'Total Capacity',
avg_channel_size: 'Avg. Channel Size', avg_channel_size: 'Avg. Channel Size',
biggest_channel_size: 'Biggest Channel Size', biggest_channel_size: 'Biggest Channel Size',
@@ -33,6 +35,8 @@ window.localisation.en = {
reset_defaults_tooltip: 'Delete all settings and reset to defaults.', reset_defaults_tooltip: 'Delete all settings and reset to defaults.',
download_backup: 'Download database backup', download_backup: 'Download database backup',
name_your_wallet: 'Name your %{name} wallet', name_your_wallet: 'Name your %{name} wallet',
wallet_topup_ok:
'Success creating virtual funds (%{amount} sats). Payments depend on actual funds on funding source.',
paste_invoice_label: 'Paste an invoice, payment request or lnurl code *', paste_invoice_label: 'Paste an invoice, payment request or lnurl code *',
lnbits_description: lnbits_description:
'Easy to set up and lightweight, LNbits can run on any Lightning Network funding source and even LNbits itself! You can run LNbits for yourself, or easily offer a custodian solution for others. Each wallet has its own API keys and there is no limit to the number of wallets you can make. Being able to partition funds makes LNbits a useful tool for money management and as a development tool. Extensions add extra functionality to LNbits so you can experiment with a range of cutting-edge technologies on the lightning network. We have made developing extensions as easy as possible, and as a free and open-source project, we encourage people to develop and submit their own.', 'Easy to set up and lightweight, LNbits can run on any Lightning Network funding source and even LNbits itself! You can run LNbits for yourself, or easily offer a custodian solution for others. Each wallet has its own API keys and there is no limit to the number of wallets you can make. Being able to partition funds makes LNbits a useful tool for money management and as a development tool. Extensions add extra functionality to LNbits so you can experiment with a range of cutting-edge technologies on the lightning network. We have made developing extensions as easy as possible, and as a free and open-source project, we encourage people to develop and submit their own.',
@@ -98,11 +102,8 @@ window.localisation.en = {
i_understand: 'I understand', i_understand: 'I understand',
copy_wallet_url: 'Copy wallet URL', copy_wallet_url: 'Copy wallet URL',
disclaimer_dialog_title: 'Important!', disclaimer_dialog_title: 'Important!',
disclaimer_dialog: `You *must* save your login credentials to be able to access your wallet again.If you lose them, you will lose access to your wallet and funds. disclaimer_dialog:
'You *must* save your login credentials to be able to access your wallet again. If you lose them, you will lose access to your wallet and funds.\n\nFind your login credentials on your account settings page.\n\nThis service is in BETA. LNbits holds no responsibility for loss of access to funds.',
Find your login credentials on your account settings page.
This service is in BETA. LNbits holds no responsibility for loss of access to funds.`,
no_transactions: 'No transactions made yet', no_transactions: 'No transactions made yet',
manage: 'Manage', manage: 'Manage',
extensions: 'Extensions', extensions: 'Extensions',
@@ -246,5 +247,6 @@ This service is in BETA. LNbits holds no responsibility for loss of access to fu
pay_from_wallet: 'Pay from Wallet', pay_from_wallet: 'Pay from Wallet',
show_qr: 'Show QR', show_qr: 'Show QR',
retry_install: 'Retry Install', retry_install: 'Retry Install',
new_payment: 'Make New Payment' new_payment: 'Make New Payment',
hide_empty_wallets: 'Hide empty wallets'
} }
+9 -1
View File
@@ -99,6 +99,7 @@ window.localisation.es = {
'Este es un código QR LNURL-withdraw para drenar todos los fondos de esta billetera. No lo comparta con nadie. Es compatible con balanceCheck y balanceNotify, por lo que su billetera puede continuar drenando los fondos de aquí después del primer drenaje.', 'Este es un código QR LNURL-withdraw para drenar todos los fondos de esta billetera. No lo comparta con nadie. Es compatible con balanceCheck y balanceNotify, por lo que su billetera puede continuar drenando los fondos de aquí después del primer drenaje.',
i_understand: 'Lo entiendo', i_understand: 'Lo entiendo',
copy_wallet_url: 'Copiar URL de billetera', copy_wallet_url: 'Copiar URL de billetera',
disclaimer_dialog_title: '¡Importante!',
disclaimer_dialog: disclaimer_dialog:
'La funcionalidad de inicio de sesión se lanzará en una actualización futura, por ahora, asegúrese de guardar esta página como marcador para acceder a su billetera en el futuro. Este servicio está en BETA y no asumimos ninguna responsabilidad por personas que pierdan el acceso a sus fondos.', 'La funcionalidad de inicio de sesión se lanzará en una actualización futura, por ahora, asegúrese de guardar esta página como marcador para acceder a su billetera en el futuro. Este servicio está en BETA y no asumimos ninguna responsabilidad por personas que pierdan el acceso a sus fondos.',
no_transactions: 'No hay transacciones todavía', no_transactions: 'No hay transacciones todavía',
@@ -243,5 +244,12 @@ window.localisation.es = {
logout: 'Cerrar sesión', logout: 'Cerrar sesión',
look_and_feel: 'Apariencia', look_and_feel: 'Apariencia',
language: 'Idioma', language: 'Idioma',
color_scheme: 'Esquema de colores' color_scheme: 'Esquema de colores',
extension_cost: 'Esta versión requiere un pago mínimo de %{cost} sats.',
extension_paid_sats: 'Ya has pagado %{paid_sats} sats.',
release_details_error: 'No se pueden obtener los detalles de la versión.',
pay_from_wallet: 'Pagar desde la billetera',
show_qr: 'Mostrar QR',
retry_install: 'Reintentar Instalación',
new_payment: 'Realizar nuevo pago'
} }
+10 -2
View File
@@ -64,7 +64,7 @@ window.localisation.fi = {
service_fee_tooltip: service_fee_tooltip:
'LNBits palvelimen ylläpitäjä veloittaa lähtevästä maksusta palvelumaksun.', 'LNBits palvelimen ylläpitäjä veloittaa lähtevästä maksusta palvelumaksun.',
toggle_darkmode: 'Tumma näkymä', toggle_darkmode: 'Tumma näkymä',
toggle_reactions: 'Käytä tapahtuma efektejä', payment_reactions: 'Maksureaktiot',
view_swagger_docs: 'Näytä LNbits Swagger API-dokumentit', view_swagger_docs: 'Näytä LNbits Swagger API-dokumentit',
api_docs: 'API-dokumentaatio', api_docs: 'API-dokumentaatio',
api_keys_api_docs: 'Solmun URL, API-avaimet ja -dokumentaatio', api_keys_api_docs: 'Solmun URL, API-avaimet ja -dokumentaatio',
@@ -102,6 +102,7 @@ window.localisation.fi = {
'Tämä LNURL-withdraw -tyyppinen QR-koodi on tarkoitettu kaikkien varojen imurointiin lompakosta. ÄLÄ JAA SITÄ KENELLEKÄÄN! Se on balanceCheck- ja balanceNotify-toimintojen kanssa yhteensopiva, joten sitä voi käyttää lompakon tyhjentämiseen ensimmäisen käytön jälleen jatkuvasti.', 'Tämä LNURL-withdraw -tyyppinen QR-koodi on tarkoitettu kaikkien varojen imurointiin lompakosta. ÄLÄ JAA SITÄ KENELLEKÄÄN! Se on balanceCheck- ja balanceNotify-toimintojen kanssa yhteensopiva, joten sitä voi käyttää lompakon tyhjentämiseen ensimmäisen käytön jälleen jatkuvasti.',
i_understand: 'Vakuutan ymmärtäväni', i_understand: 'Vakuutan ymmärtäväni',
copy_wallet_url: 'Kopioi lompakon URL', copy_wallet_url: 'Kopioi lompakon URL',
disclaimer_dialog_title: 'Tärkeää!',
disclaimer_dialog: disclaimer_dialog:
'Muistathan tallettaa kirjautumistietosi turvallisesta ja helposti saataville, jotta pääset jatkossakin kirjautumaan lompakkoosi! Tutustu myös Tilin asetukset -sivuun. Tämä palvelu on kokeiluvaiheessa (eli BETA), ja niinpä kukaan ei ota mitään vastuuta varojen säilymisestä tai niiden käytettävyyden takaamisesta.', 'Muistathan tallettaa kirjautumistietosi turvallisesta ja helposti saataville, jotta pääset jatkossakin kirjautumaan lompakkoosi! Tutustu myös Tilin asetukset -sivuun. Tämä palvelu on kokeiluvaiheessa (eli BETA), ja niinpä kukaan ei ota mitään vastuuta varojen säilymisestä tai niiden käytettävyyden takaamisesta.',
no_transactions: 'Lompakossa ei ole yhtään tapahtumaa', no_transactions: 'Lompakossa ei ole yhtään tapahtumaa',
@@ -241,5 +242,12 @@ window.localisation.fi = {
logout: 'Poistu', logout: 'Poistu',
look_and_feel: 'Kieli ja värit', look_and_feel: 'Kieli ja värit',
language: 'Kieli', language: 'Kieli',
color_scheme: 'Väriteema' color_scheme: 'Väriteema',
extension_cost: 'Tämä julkaisu edellyttää vähintään %{cost} satsin maksua.',
extension_paid_sats: 'Olet jo maksanut %{paid_sats} satsia.',
release_details_error: 'Ei voi hakea julkaisun tietoja.',
pay_from_wallet: 'Maksa lompakosta',
show_qr: 'Näytä QR',
retry_install: 'Yritä asennusta uudelleen',
new_payment: 'Tee uusi maksu'
} }
+10 -1
View File
@@ -103,6 +103,7 @@ window.localisation.fr = {
"Il s'agit d'un code QR LNURL-withdraw pour tout aspirer de ce portefeuille. Ne le partagez avec personne. Il est compatible avec balanceCheck et balanceNotify, de sorte que votre portefeuille peut continuer à retirer les fonds continuellement à partir d'ici après le premier retrait.", "Il s'agit d'un code QR LNURL-withdraw pour tout aspirer de ce portefeuille. Ne le partagez avec personne. Il est compatible avec balanceCheck et balanceNotify, de sorte que votre portefeuille peut continuer à retirer les fonds continuellement à partir d'ici après le premier retrait.",
i_understand: "J'ai compris", i_understand: "J'ai compris",
copy_wallet_url: "Copier l'URL du portefeuille", copy_wallet_url: "Copier l'URL du portefeuille",
disclaimer_dialog_title: 'Important !',
disclaimer_dialog: disclaimer_dialog:
"La fonctionnalité de connexion sera publiée dans une future mise à jour, pour l'instant, assurez-vous de mettre cette page en favori pour accéder à votre portefeuille ultérieurement ! Ce service est en BETA, et nous ne sommes pas responsables des personnes qui perdent l'accès à leurs fonds.", "La fonctionnalité de connexion sera publiée dans une future mise à jour, pour l'instant, assurez-vous de mettre cette page en favori pour accéder à votre portefeuille ultérieurement ! Ce service est en BETA, et nous ne sommes pas responsables des personnes qui perdent l'accès à leurs fonds.",
no_transactions: 'Aucune transaction effectuée pour le moment', no_transactions: 'Aucune transaction effectuée pour le moment',
@@ -247,5 +248,13 @@ window.localisation.fr = {
logout: 'Déconnexion', logout: 'Déconnexion',
look_and_feel: 'Apparence', look_and_feel: 'Apparence',
language: 'Langue', language: 'Langue',
color_scheme: 'Schéma de couleurs' color_scheme: 'Schéma de couleurs',
extension_cost:
'Cette version nécessite un paiement minimum de %{cost} sats.',
extension_paid_sats: 'Vous avez déjà payé %{paid_sats} sats.',
release_details_error: "Impossible d'obtenir les détails de la version.",
pay_from_wallet: 'Payer depuis le portefeuille',
show_qr: 'Afficher le QR',
retry_install: "Réessayer l'installation",
new_payment: 'Effectuer un nouveau paiement'
} }
+10 -1
View File
@@ -100,6 +100,7 @@ window.localisation.it = {
'Questo è un codice QR <code>LNURL-withdraw</code> per prelevare tutti i fondi da questo portafoglio. Non condividerlo con nessuno. È compatibile con <code>balanceCheck</code> e <code>balanceNotify</code>, di conseguenza il vostro portafoglio può continuare a prelevare continuamente i fondi da qui dopo il primo prelievo', 'Questo è un codice QR <code>LNURL-withdraw</code> per prelevare tutti i fondi da questo portafoglio. Non condividerlo con nessuno. È compatibile con <code>balanceCheck</code> e <code>balanceNotify</code>, di conseguenza il vostro portafoglio può continuare a prelevare continuamente i fondi da qui dopo il primo prelievo',
i_understand: 'Ho capito', i_understand: 'Ho capito',
copy_wallet_url: 'Copia URL portafoglio', copy_wallet_url: 'Copia URL portafoglio',
disclaimer_dialog_title: 'Importante!',
disclaimer_dialog: disclaimer_dialog:
"La funzionalità di login sarà rilasciata in un futuro aggiornamento; per ora, assicuratevi di salvare tra i preferiti questa pagina per accedere nuovamente in futuro a questo portafoglio! Questo servizio è in fase BETA e non ci assumiamo alcuna responsabilità per la perdita all'accesso dei fondi", "La funzionalità di login sarà rilasciata in un futuro aggiornamento; per ora, assicuratevi di salvare tra i preferiti questa pagina per accedere nuovamente in futuro a questo portafoglio! Questo servizio è in fase BETA e non ci assumiamo alcuna responsabilità per la perdita all'accesso dei fondi",
no_transactions: 'Nessuna transazione effettuata', no_transactions: 'Nessuna transazione effettuata',
@@ -244,5 +245,13 @@ window.localisation.it = {
logout: 'Esci', logout: 'Esci',
look_and_feel: 'Aspetto e Comportamento', look_and_feel: 'Aspetto e Comportamento',
language: 'Lingua', language: 'Lingua',
color_scheme: 'Schema dei colori' color_scheme: 'Schema dei colori',
extension_cost:
'Questa versione richiede un pagamento minimo di %{cost} satoshi.',
extension_paid_sats: 'Hai già pagato %{paid_sats} sats.',
release_details_error: 'Impossibile ottenere i dettagli della versione.',
pay_from_wallet: 'Paga dal Portafoglio',
show_qr: 'Mostra QR',
retry_install: 'Riprova Installazione',
new_payment: 'Effettua Nuovo Pagamento'
} }
+9 -1
View File
@@ -97,6 +97,7 @@ window.localisation.jp = {
drain_funds_desc: 'ウォレットの残高をすべて他のウォレットに送金します', drain_funds_desc: 'ウォレットの残高をすべて他のウォレットに送金します',
i_understand: '理解した', i_understand: '理解した',
copy_wallet_url: 'ウォレットURLをコピー', copy_wallet_url: 'ウォレットURLをコピー',
disclaimer_dialog_title: '重要!',
disclaimer_dialog: disclaimer_dialog:
'ウォレットを削除すると、ウォレットの秘密鍵が削除され、ウォレットを復元することはできません。ウォレットを削除する前に、ウォレットをエクスポートしてください。', 'ウォレットを削除すると、ウォレットの秘密鍵が削除され、ウォレットを復元することはできません。ウォレットを削除する前に、ウォレットをエクスポートしてください。',
no_transactions: 'トランザクションはありません', no_transactions: 'トランザクションはありません',
@@ -240,5 +241,12 @@ window.localisation.jp = {
logout: 'ログアウト', logout: 'ログアウト',
look_and_feel: 'ルック・アンド・フィール', look_and_feel: 'ルック・アンド・フィール',
language: '言語', language: '言語',
color_scheme: 'カラースキーム' color_scheme: 'カラースキーム',
extension_cost: 'このリリースには最低 %{cost} サトシの支払いが必要です。',
extension_paid_sats: 'すでに%{paid_sats} satsを支払いました。',
release_details_error: 'リリースの詳細を取得できません。',
pay_from_wallet: 'ウォレットから支払う',
show_qr: 'QRを表示',
retry_install: '再試行インストール',
new_payment: '新しい支払いを作成する'
} }
+9 -1
View File
@@ -98,6 +98,7 @@ window.localisation.kr = {
'이는 선택된 지갑으로부터 모든 자금을 인출하는 LNURL-withdraw QR 코드입니다. 그 누구와도 공유하지 마세요. balanceCheck 및 balanceNotify 기능과 호환되며, 당신의 지갑은 첫 출금 이후로도 계속 자금을 끌어당기고 있을 수 있습니다.', '이는 선택된 지갑으로부터 모든 자금을 인출하는 LNURL-withdraw QR 코드입니다. 그 누구와도 공유하지 마세요. balanceCheck 및 balanceNotify 기능과 호환되며, 당신의 지갑은 첫 출금 이후로도 계속 자금을 끌어당기고 있을 수 있습니다.',
i_understand: '이해하였습니다', i_understand: '이해하였습니다',
copy_wallet_url: '지갑 URL 복사하기', copy_wallet_url: '지갑 URL 복사하기',
disclaimer_dialog_title: '중요!',
disclaimer_dialog: disclaimer_dialog:
'로그인 기능은 향후 업데이트를 통해 지원될 계획이지만, 현재로써는 이 페이지에 향후 다시 접속하기 위해 북마크 설정하는 것을 잊지 마세요! 이 서비스는 아직 BETA 과정에 있고, LNbits 개발자들은 자금 손실에 대해 전혀 책임을 지지 않습니다.', '로그인 기능은 향후 업데이트를 통해 지원될 계획이지만, 현재로써는 이 페이지에 향후 다시 접속하기 위해 북마크 설정하는 것을 잊지 마세요! 이 서비스는 아직 BETA 과정에 있고, LNbits 개발자들은 자금 손실에 대해 전혀 책임을 지지 않습니다.',
no_transactions: '아직 아무런 거래도 이루어지지 않았습니다', no_transactions: '아직 아무런 거래도 이루어지지 않았습니다',
@@ -237,5 +238,12 @@ window.localisation.kr = {
logout: '로그아웃', logout: '로그아웃',
look_and_feel: '외관과 느낌', look_and_feel: '외관과 느낌',
language: '언어', language: '언어',
color_scheme: '색상 구성' color_scheme: '색상 구성',
extension_cost: '이 버전은 최소 %{cost} sats의 지불이 필요합니다.',
extension_paid_sats: '당신은 이미 %{paid_sats} sats를 지불했습니다.',
release_details_error: '릴리스 세부 정보를 가져올 수 없습니다.',
pay_from_wallet: '지갑에서 결제하다',
show_qr: 'QR 보기',
retry_install: '다시 설치하세요',
new_payment: '새로운 결제하기'
} }
+10 -1
View File
@@ -101,6 +101,7 @@ window.localisation.nl = {
'Dit is een LNURL-withdraw QR-code om alles uit deze portemonnee te halen. Deel deze code niet met anderen. Het is compatibel met balanceCheck en balanceNotify zodat jouw portemonnee continu geld kan blijven opnemen vanaf hier na de eerste opname.', 'Dit is een LNURL-withdraw QR-code om alles uit deze portemonnee te halen. Deel deze code niet met anderen. Het is compatibel met balanceCheck en balanceNotify zodat jouw portemonnee continu geld kan blijven opnemen vanaf hier na de eerste opname.',
i_understand: 'Ik begrijp het', i_understand: 'Ik begrijp het',
copy_wallet_url: 'Kopieer portemonnee-URL', copy_wallet_url: 'Kopieer portemonnee-URL',
disclaimer_dialog_title: 'Belangrijk!',
disclaimer_dialog: disclaimer_dialog:
'Inlogfunctionaliteit wordt uitgebracht in een toekomstige update. Zorg er nu voor dat je deze pagina als favoriet markeert om in de toekomst toegang te krijgen tot je portemonnee! Deze service is in BETA en we zijn niet verantwoordelijk voor mensen die de toegang tot hun fondsen verliezen.', 'Inlogfunctionaliteit wordt uitgebracht in een toekomstige update. Zorg er nu voor dat je deze pagina als favoriet markeert om in de toekomst toegang te krijgen tot je portemonnee! Deze service is in BETA en we zijn niet verantwoordelijk voor mensen die de toegang tot hun fondsen verliezen.',
no_transactions: 'Er zijn nog geen transacties gedaan', no_transactions: 'Er zijn nog geen transacties gedaan',
@@ -243,5 +244,13 @@ window.localisation.nl = {
logout: 'Afmelden', logout: 'Afmelden',
look_and_feel: 'Uiterlijk en gedrag', look_and_feel: 'Uiterlijk en gedrag',
language: 'Taal', language: 'Taal',
color_scheme: 'Kleurenschema' color_scheme: 'Kleurenschema',
extension_cost:
'Deze release vereist een betaling van minimaal %{cost} sats.',
extension_paid_sats: 'U heeft al %{paid_sats} sats betaald.',
release_details_error: 'Kan de gegevens van de release niet ophalen.',
pay_from_wallet: 'Betalen vanuit Portemonnee',
show_qr: 'Toon QR',
retry_install: 'Opnieuw installeren',
new_payment: 'Nieuwe betaling maken'
} }
+10 -1
View File
@@ -100,6 +100,7 @@ window.localisation.pi = {
'This be an LNURL-withdraw QR code for slurpin everything from this wallet. Don`t share with anyone. It be compatible with balanceCheck and balanceNotify so yer wallet may keep pullin` the funds continuously from here after the first withdraw.', 'This be an LNURL-withdraw QR code for slurpin everything from this wallet. Don`t share with anyone. It be compatible with balanceCheck and balanceNotify so yer wallet may keep pullin` the funds continuously from here after the first withdraw.',
i_understand: 'I understand, yo ho ho and a bottle of rum!', i_understand: 'I understand, yo ho ho and a bottle of rum!',
copy_wallet_url: 'Copy wallet URL like a map, savvy', copy_wallet_url: 'Copy wallet URL like a map, savvy',
disclaimer_dialog_title: 'Avast!',
disclaimer_dialog: disclaimer_dialog:
'Login functionality to be released in a future update, for now, make sure ye bookmark this page for future access to your booty! This service be in BETA, and we hold no responsibility for people losing access to doubloons.', 'Login functionality to be released in a future update, for now, make sure ye bookmark this page for future access to your booty! This service be in BETA, and we hold no responsibility for people losing access to doubloons.',
no_transactions: 'No transactions made yet, me hearties. Belay that!', no_transactions: 'No transactions made yet, me hearties. Belay that!',
@@ -240,5 +241,13 @@ window.localisation.pi = {
logout: 'Log out yer session', logout: 'Log out yer session',
look_and_feel: 'Look and Feel', look_and_feel: 'Look and Feel',
language: 'Langwidge', language: 'Langwidge',
color_scheme: 'Colour Scheme' color_scheme: 'Colour Scheme',
extension_cost:
"This release be needin' a payment o' minimum %{cost} sats, arr.",
extension_paid_sats: 'Ye have already paid %{paid_sats} sats.',
release_details_error: "Cannot get th' release details.",
pay_from_wallet: 'Pay from ye Wallet',
show_qr: 'Show QR',
retry_install: "Try 'nstallin' Again",
new_payment: 'Make New Payment'
} }
+10 -1
View File
@@ -98,6 +98,7 @@ window.localisation.pl = {
'To jest kod QR służący do opróżnienia portfela (LNURL-withdraw). Nie udostępniaj go nikomu. Ten kod jest kompatybilny z funkcjami, które umożliwiają wielokrotne żądania aż do zupełnego opróżnienia portfela.', 'To jest kod QR służący do opróżnienia portfela (LNURL-withdraw). Nie udostępniaj go nikomu. Ten kod jest kompatybilny z funkcjami, które umożliwiają wielokrotne żądania aż do zupełnego opróżnienia portfela.',
i_understand: 'Rozumiem', i_understand: 'Rozumiem',
copy_wallet_url: 'Skopiuj URL portfela', copy_wallet_url: 'Skopiuj URL portfela',
disclaimer_dialog_title: 'Ważne!',
disclaimer_dialog: disclaimer_dialog:
'Funkcja logowania zostanie uruchomiona w przyszłości. Póki co upewnij się, że zapisałeś adres URL tej strony aby mieć dostęp do tego portfela. Nie udostępniaj adresu tej strony nikomu, kto nie ma mieć do tego portfela dostępu! Ta usługa działa w wersji BETA, nie odpowiadamy za utratę dostępu do środków przez osoby używające LNbits.', 'Funkcja logowania zostanie uruchomiona w przyszłości. Póki co upewnij się, że zapisałeś adres URL tej strony aby mieć dostęp do tego portfela. Nie udostępniaj adresu tej strony nikomu, kto nie ma mieć do tego portfela dostępu! Ta usługa działa w wersji BETA, nie odpowiadamy za utratę dostępu do środków przez osoby używające LNbits.',
no_transactions: 'Brak transakcji', no_transactions: 'Brak transakcji',
@@ -239,5 +240,13 @@ window.localisation.pl = {
logout: 'Wyloguj', logout: 'Wyloguj',
look_and_feel: 'Wygląd i zachowanie', look_and_feel: 'Wygląd i zachowanie',
language: 'Język', language: 'Język',
color_scheme: 'Schemat kolorów' color_scheme: 'Schemat kolorów',
extension_cost:
'To niniejsze wydanie wymaga zapłaty minimalnej %{cost} satów.',
extension_paid_sats: 'Już zapłaciłeś %{paid_sats} satów.',
release_details_error: 'Nie można uzyskać szczegółów wydania.',
pay_from_wallet: 'Zapłać z portfela',
show_qr: 'Pokaż kod QR',
retry_install: 'Ponów instalację',
new_payment: 'Dokonaj nowej płatności'
} }
+9 -1
View File
@@ -99,6 +99,7 @@ window.localisation.pt = {
'Este é um código QR de saque LNURL para sacar tudo desta carteira. Não o partilhe com ninguém. É compatível com balanceCheck e balanceNotify para que a sua carteira possa continuar levantando os fundos continuamente daqui após o primeiro saque.', 'Este é um código QR de saque LNURL para sacar tudo desta carteira. Não o partilhe com ninguém. É compatível com balanceCheck e balanceNotify para que a sua carteira possa continuar levantando os fundos continuamente daqui após o primeiro saque.',
i_understand: 'Eu entendo', i_understand: 'Eu entendo',
copy_wallet_url: 'Copiar URL da carteira', copy_wallet_url: 'Copiar URL da carteira',
disclaimer_dialog_title: 'Importante!',
disclaimer_dialog: disclaimer_dialog:
'Funcionalidade de login a ser lançada numa atualização futura, por enquanto, certifique-se que marca esta página para acesso futuro à sua carteira! Este serviço está em BETA, e não nos responsabilizamos por pessoas que perderem o acesso aos fundos.', 'Funcionalidade de login a ser lançada numa atualização futura, por enquanto, certifique-se que marca esta página para acesso futuro à sua carteira! Este serviço está em BETA, e não nos responsabilizamos por pessoas que perderem o acesso aos fundos.',
no_transactions: 'Ainda não foram feitas transações', no_transactions: 'Ainda não foram feitas transações',
@@ -240,5 +241,12 @@ window.localisation.pt = {
logout: 'Sair', logout: 'Sair',
look_and_feel: 'Aparência e Sensação', look_and_feel: 'Aparência e Sensação',
language: 'Idioma', language: 'Idioma',
color_scheme: 'Esquema de Cores' color_scheme: 'Esquema de Cores',
extension_cost: 'Este lançamento requer um pagamento mínimo de %{cost} sats.',
extension_paid_sats: 'Você já pagou %{paid_sats} sats.',
release_details_error: 'Não é possível obter os detalhes da versão.',
pay_from_wallet: 'Pague da Carteira',
show_qr: 'Exibir QR',
retry_install: 'Reinstalar Tente Novamente',
new_payment: 'Realizar Novo Pagamento'
} }
+9 -1
View File
@@ -98,6 +98,7 @@ window.localisation.sk = {
'Toto je LNURL-withdraw QR kód pre vyprázdnienie všetkého z tejto peňaženky. S nikým ho nezdieľajte. Je kompatibilný s balanceCheck a balanceNotify, takže vaša peňaženka môže naďalej kontinuálne vyťahovať prostriedky odtiaľto po prvom výbere.', 'Toto je LNURL-withdraw QR kód pre vyprázdnienie všetkého z tejto peňaženky. S nikým ho nezdieľajte. Je kompatibilný s balanceCheck a balanceNotify, takže vaša peňaženka môže naďalej kontinuálne vyťahovať prostriedky odtiaľto po prvom výbere.',
i_understand: 'Rozumiem', i_understand: 'Rozumiem',
copy_wallet_url: 'Kopírovať URL peňaženky', copy_wallet_url: 'Kopírovať URL peňaženky',
disclaimer_dialog_title: 'Dôležité!',
disclaimer_dialog: disclaimer_dialog:
'Funkcionalita prihlásenia bude vydaná v budúcej aktualizácii, zatiaľ si uistite, že ste si túto stránku pridali medzi záložky pre budúci prístup k vašej peňaženke! Táto služba je v BETA verzii a nenesieme zodpovednosť za stratu prístupu k prostriedkom.', 'Funkcionalita prihlásenia bude vydaná v budúcej aktualizácii, zatiaľ si uistite, že ste si túto stránku pridali medzi záložky pre budúci prístup k vašej peňaženke! Táto služba je v BETA verzii a nenesieme zodpovednosť za stratu prístupu k prostriedkom.',
no_transactions: 'Zatiaľ žiadne transakcie', no_transactions: 'Zatiaľ žiadne transakcie',
@@ -239,5 +240,12 @@ window.localisation.sk = {
logout: 'Odhlásiť sa', logout: 'Odhlásiť sa',
look_and_feel: 'Vzhľad a dojem', look_and_feel: 'Vzhľad a dojem',
language: 'Jazyk', language: 'Jazyk',
color_scheme: 'Farebná schéma' color_scheme: 'Farebná schéma',
extension_cost: 'Táto verzia vyžaduje minimálnu platbu %{cost} satoshi.',
extension_paid_sats: 'Už ste zaplatili %{paid_sats} sats.',
release_details_error: 'Nepodarilo sa získať podrobnosti o vydaní.',
pay_from_wallet: 'Zaplatiť z peňaženky',
show_qr: 'Zobraziť QR',
retry_install: 'Skúste inštaláciu znova',
new_payment: 'Vytvoriť novú platbu'
} }
+9 -1
View File
@@ -99,6 +99,7 @@ window.localisation.we = {
'Cod QR Tynnu`n ôl LNURL yw hwn ar gyfer slurpio popeth o`r waled hon. Peidiwch â rhannu gyda neb. Mae`n gydnaws â balanceCheck a balanceNotify felly efallai y bydd eich waled yn tynnu`r arian yn barhaus o`r fan hon ar ôl y codiad cyntaf.', 'Cod QR Tynnu`n ôl LNURL yw hwn ar gyfer slurpio popeth o`r waled hon. Peidiwch â rhannu gyda neb. Mae`n gydnaws â balanceCheck a balanceNotify felly efallai y bydd eich waled yn tynnu`r arian yn barhaus o`r fan hon ar ôl y codiad cyntaf.',
i_understand: 'Rwy`n deall', i_understand: 'Rwy`n deall',
copy_wallet_url: 'Copi URL waled', copy_wallet_url: 'Copi URL waled',
disclaimer_dialog_title: 'Pwysig!',
disclaimer_dialog: disclaimer_dialog:
'Swyddogaeth mewngofnodi i`w ryddhau mewn diweddariad yn y dyfodol, am y tro, gwnewch yn siŵr eich bod yn rhoi nod tudalen ar y dudalen hon ar gyfer mynediad i`ch waled yn y dyfodol! Mae`r gwasanaeth hwn yn BETA, ac nid ydym yn gyfrifol am bobl sy`n colli mynediad at arian.', 'Swyddogaeth mewngofnodi i`w ryddhau mewn diweddariad yn y dyfodol, am y tro, gwnewch yn siŵr eich bod yn rhoi nod tudalen ar y dudalen hon ar gyfer mynediad i`ch waled yn y dyfodol! Mae`r gwasanaeth hwn yn BETA, ac nid ydym yn gyfrifol am bobl sy`n colli mynediad at arian.',
no_transactions: 'Dim trafodion wedi`u gwneud eto', no_transactions: 'Dim trafodion wedi`u gwneud eto',
@@ -239,5 +240,12 @@ window.localisation.we = {
logout: 'Allgofnodi', logout: 'Allgofnodi',
look_and_feel: 'Edrych a Theimlo', look_and_feel: 'Edrych a Theimlo',
language: 'Iaith', language: 'Iaith',
color_scheme: 'Cynllun Lliw' color_scheme: 'Cynllun Lliw',
extension_cost: "Mae'r rhyddhad hwn yn gofyn am daliad o leiaf %{cost} sats.",
extension_paid_sats: 'Rydych chi eisoes wedi talu %{paid_sats} sats.',
release_details_error: 'Methu cael manylion y rhyddhau.',
pay_from_wallet: "Talu o'r Waled",
show_qr: 'Dangos QR',
retry_install: 'Ailgeisio Gosod',
new_payment: 'Gwneud Taliad Newydd'
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

+12 -25
View File
@@ -44,9 +44,18 @@ new Vue({
isSuperUser: false, isSuperUser: false,
wallet: {}, wallet: {},
cancel: {}, cancel: {},
topUpDialog: { colors: [
show: false 'primary',
}, 'secondary',
'accent',
'positive',
'negative',
'info',
'warning',
'red',
'yellow',
'orange'
],
tab: 'funding', tab: 'funding',
needsRestart: false needsRestart: false
} }
@@ -72,7 +81,6 @@ new Vue({
let addUser = this.formAddAdmin let addUser = this.formAddAdmin
let admin_users = this.formData.lnbits_admin_users let admin_users = this.formData.lnbits_admin_users
if (addUser && addUser.length && !admin_users.includes(addUser)) { if (addUser && addUser.length && !admin_users.includes(addUser)) {
//admin_users = [...admin_users, addUser]
this.formData.lnbits_admin_users = [...admin_users, addUser] this.formData.lnbits_admin_users = [...admin_users, addUser]
this.formAddAdmin = '' this.formAddAdmin = ''
} }
@@ -188,27 +196,6 @@ new Vue({
LNbits.utils.notifyApiError(error) LNbits.utils.notifyApiError(error)
}) })
}, },
topupWallet() {
LNbits.api
.request(
'PUT',
'/admin/api/v1/topup/',
this.g.user.wallets[0].adminkey,
this.wallet
)
.then(response => {
this.$q.notify({
type: 'positive',
message:
'Success! Added ' + this.wallet.amount + ' to ' + this.wallet.id,
icon: null
})
this.wallet = {}
})
.catch(function (error) {
LNbits.utils.notifyApiError(error)
})
},
formatDate(date) { formatDate(date) {
return moment(date * 1000).fromNow() return moment(date * 1000).fromNow()
}, },
+6 -18
View File
@@ -33,8 +33,8 @@ window.LNbits = {
out: false, out: false,
amount: amount, amount: amount,
memo: memo, memo: memo,
unit: unit, lnurl_callback: lnurlCallback,
lnurl_callback: lnurlCallback unit: unit
}) })
}, },
payInvoice: function (wallet, bolt11) { payInvoice: function (wallet, bolt11) {
@@ -145,22 +145,10 @@ window.LNbits = {
) )
}, },
updateBalance: function (credit, wallet_id) { updateBalance: function (credit, wallet_id) {
return LNbits.api return LNbits.api.request('PUT', '/users/api/v1/topup', null, {
.request('PUT', '/admin/api/v1/topup/', null, { amount: credit,
amount: credit, id: wallet_id
id: wallet_id })
})
.then(_ => {
Quasar.Notify.create({
type: 'positive',
message: 'Success! Added ' + credit + ' sats to ' + wallet_id,
icon: null
})
return parseInt(credit)
})
.catch(function (error) {
LNbits.utils.notifyApiError(error)
})
} }
}, },
events: { events: {
+37 -6
View File
@@ -170,7 +170,7 @@ Vue.component('lnbits-extension-list', {
}) })
Vue.component('lnbits-manage', { Vue.component('lnbits-manage', {
props: ['showAdmin', 'showNode', 'showExtensions'], props: ['showAdmin', 'showNode', 'showExtensions', 'showUsers'],
methods: { methods: {
isActive: function (path) { isActive: function (path) {
return window.location.pathname === path return window.location.pathname === path
@@ -202,6 +202,14 @@ Vue.component('lnbits-manage', {
<q-item-label lines="1" v-text="$t('node')"></q-item-label> <q-item-label lines="1" v-text="$t('node')"></q-item-label>
</q-item-section> </q-item-section>
</q-item> </q-item>
<q-item v-if="showUsers" clickable tag="a" href="/users" :active="isActive('/users')">
<q-item-section side>
<q-icon name="groups" :color="isActive('/users') ? 'primary' : 'grey-5'" size="md"></q-icon>
</q-item-section>
<q-item-section>
<q-item-label lines="1" v-text="$t('users')"></q-item-label>
</q-item-section>
</q-item>
</div> </div>
<q-item v-if="showExtensions" clickable tag="a" href="/extensions" :active="isActive('/extensions')"> <q-item v-if="showExtensions" clickable tag="a" href="/extensions" :active="isActive('/extensions')">
<q-item-section side> <q-item-section side>
@@ -318,8 +326,8 @@ Vue.component('lnbits-payment-details', {
this.payment.webhook_status < 0 this.payment.webhook_status < 0
? 'red-10' ? 'red-10'
: !this.payment.webhook_status : !this.payment.webhook_status
? 'cyan-7' ? 'cyan-7'
: 'green-10' : 'green-10'
}, },
webhookStatusText() { webhookStatusText() {
return this.payment.webhook_status return this.payment.webhook_status
@@ -691,9 +699,32 @@ Vue.component('lnbits-update-balance', {
}, },
methods: { methods: {
updateBalance: function (credit) { updateBalance: function (credit) {
LNbits.api.updateBalance(credit, this.wallet_id).then(res => { LNbits.api
this.callback({value: res, wallet_id: this.wallet_id}) .updateBalance(credit, this.wallet_id)
}) .then(res => {
if (res.data.status !== 'Success') {
throw new Error(res.data)
}
this.callback({
success: true,
credit: parseInt(credit),
wallet_id: this.wallet_id
})
})
.then(_ => {
credit = parseInt(credit)
this.$q.notify({
type: 'positive',
message: this.$t('wallet_topup_ok', {
amount: credit
}),
icon: null
})
return credit
})
.catch(function (error) {
LNbits.utils.notifyApiError(error)
})
} }
}, },
template: ` template: `
@@ -31,7 +31,8 @@ Vue.component('lnbits-funding-sources', {
'CoreLightningWallet', 'CoreLightningWallet',
'Core Lightning', 'Core Lightning',
{ {
corelightning_rpc: 'Endpoint' corelightning_rpc: 'Endpoint',
corelightning_pay_command: 'Custom Pay Command'
} }
], ],
[ [
@@ -114,6 +115,14 @@ Vue.component('lnbits-funding-sources', {
zbd_api_key: 'Key' zbd_api_key: 'Key'
} }
], ],
[
'PhoenixdWallet',
'Phoenixd',
{
phoenixd_api_endpoint: 'Endpoint',
phoenixd_api_password: 'Key'
}
],
[ [
'OpenNodeWallet', 'OpenNodeWallet',
'OpenNode', 'OpenNode',
@@ -0,0 +1,157 @@
function generateChart(canvas, rawData) {
const data = rawData.reduce(
(previous, current) => {
previous.labels.push(current.date)
previous.income.push(current.income)
previous.spending.push(current.spending)
previous.cumulative.push(current.balance)
return previous
},
{
labels: [],
income: [],
spending: [],
cumulative: []
}
)
return new Chart(canvas.getContext('2d'), {
type: 'bar',
data: {
labels: data.labels,
datasets: [
{
data: data.cumulative,
type: 'line',
label: 'balance',
backgroundColor: '#673ab7', // deep-purple
borderColor: '#673ab7',
borderWidth: 4,
pointRadius: 3,
fill: false
},
{
data: data.income,
type: 'bar',
label: 'in',
barPercentage: 0.75,
backgroundColor: window.Color('rgb(76,175,80)').alpha(0.5).rgbString() // green
},
{
data: data.spending,
type: 'bar',
label: 'out',
barPercentage: 0.75,
backgroundColor: window.Color('rgb(233,30,99)').alpha(0.5).rgbString() // pink
}
]
},
options: {
title: {
text: 'Chart.js Combo Time Scale'
},
tooltips: {
mode: 'index',
intersect: false
},
scales: {
xAxes: [
{
type: 'time',
display: true,
//offset: true,
time: {
minUnit: 'hour',
stepSize: 3
}
}
]
},
// performance tweaks
animation: {
duration: 0
},
elements: {
line: {
tension: 0
}
}
}
})
}
Vue.component('payment-chart', {
name: 'payment-chart',
props: ['wallet'],
mixins: [windowMixin],
data: function () {
return {
paymentsChart: {
show: false,
group: {
value: 'hour',
label: 'Hour'
},
groupOptions: [
{value: 'hour', label: 'Hour'},
{value: 'day', label: 'Day'},
{value: 'week', label: 'Week'},
{value: 'month', label: 'Month'},
{value: 'year', label: 'Year'}
],
instance: null
}
}
},
methods: {
showChart: function () {
this.paymentsChart.show = true
LNbits.api
.request(
'GET',
'/api/v1/payments/history?group=' + this.paymentsChart.group.value,
this.wallet.adminkey
)
.then(response => {
this.$nextTick(() => {
if (this.paymentsChart.instance) {
this.paymentsChart.instance.destroy()
}
this.paymentsChart.instance = generateChart(
this.$refs.canvas,
response.data
)
})
})
.catch(err => {
LNbits.utils.notifyApiError(err)
this.paymentsChart.show = false
})
}
},
template: `
<span id="payment-chart">
<q-btn dense flat round icon="show_chart" color="grey" @click="showChart" >
<q-tooltip>
<span v-text="$t('chart_tooltip')"></span>
</q-tooltip>
</q-btn>
<q-dialog v-model="paymentsChart.show" position="top">
<q-card class="q-pa-sm" style="width: 800px; max-width: unset">
<q-card-section>
<div class="row q-gutter-sm justify-between">
<div class="text-h6">Payments Chart</div>
<q-select label="Group" filled dense v-model="paymentsChart.group"
style="min-width: 120px"
:options="paymentsChart.groupOptions"
>
</q-select>
</div>
<canvas ref="canvas" width="600" height="400"></canvas>
</q-card-section>
</q-card>
</q-dialog>
</span>
`
})
+394
View File
@@ -0,0 +1,394 @@
Vue.component('payment-list', {
name: 'payment-list',
props: ['update', 'wallet', 'mobileSimple', 'lazy'],
mixins: [windowMixin],
data: function () {
return {
denomination: LNBITS_DENOMINATION,
payments: [],
paymentsTable: {
columns: [
{
name: 'time',
align: 'left',
label: this.$t('memo') + '/' + this.$t('date'),
field: 'date',
sortable: true
},
{
name: 'amount',
align: 'right',
label: this.$t('amount') + ' (' + LNBITS_DENOMINATION + ')',
field: 'sat',
sortable: true
}
],
pagination: {
rowsPerPage: 10,
page: 1,
sortBy: 'time',
descending: true,
rowsNumber: 10
},
search: null,
loading: false
},
paymentsCSV: {
columns: [
{
name: 'pending',
align: 'left',
label: 'Pending',
field: 'pending'
},
{
name: 'memo',
align: 'left',
label: this.$t('memo'),
field: 'memo'
},
{
name: 'time',
align: 'left',
label: this.$t('date'),
field: 'date',
sortable: true
},
{
name: 'amount',
align: 'right',
label: this.$t('amount') + ' (' + LNBITS_DENOMINATION + ')',
field: 'sat',
sortable: true
},
{
name: 'fee',
align: 'right',
label: this.$t('fee') + ' (m' + LNBITS_DENOMINATION + ')',
field: 'fee'
},
{
name: 'tag',
align: 'right',
label: this.$t('tag'),
field: 'tag'
},
{
name: 'payment_hash',
align: 'right',
label: this.$t('payment_hash'),
field: 'payment_hash'
},
{
name: 'payment_proof',
align: 'right',
label: this.$t('payment_proof'),
field: 'payment_proof'
},
{
name: 'webhook',
align: 'right',
label: this.$t('webhook'),
field: 'webhook'
},
{
name: 'fiat_currency',
align: 'right',
label: 'Fiat Currency',
field: row => row.extra.wallet_fiat_currency
},
{
name: 'fiat_amount',
align: 'right',
label: 'Fiat Amount',
field: row => row.extra.wallet_fiat_amount
}
],
filter: null,
loading: false
}
}
},
computed: {
filteredPayments: function () {
var q = this.paymentsTable.search
if (!q || q === '') return this.payments
return LNbits.utils.search(this.payments, q)
},
paymentsOmitter() {
if (this.$q.screen.lt.md && this.mobileSimple) {
return this.payments.length > 0 ? [this.payments[0]] : []
}
return this.payments
},
pendingPaymentsExist: function () {
return this.payments.findIndex(payment => payment.pending) !== -1
}
},
methods: {
fetchPayments: function (props) {
const params = LNbits.utils.prepareFilterQuery(this.paymentsTable, props)
return LNbits.api
.getPayments(this.wallet, params)
.then(response => {
this.paymentsTable.loading = false
this.paymentsTable.pagination.rowsNumber = response.data.total
this.payments = response.data.data.map(obj => {
return LNbits.map.payment(obj)
})
})
.catch(err => {
this.paymentsTable.loading = false
LNbits.utils.notifyApiError(err)
})
},
paymentTableRowKey: function (row) {
return row.payment_hash + row.amount
},
exportCSV: function () {
// status is important for export but it is not in paymentsTable
// because it is manually added with payment detail link and icons
// and would cause duplication in the list
const pagination = this.paymentsTable.pagination
const query = {
sortby: pagination.sortBy ?? 'time',
direction: pagination.descending ? 'desc' : 'asc'
}
const params = new URLSearchParams(query)
LNbits.api.getPayments(this.wallet, params).then(response => {
const payments = response.data.data.map(LNbits.map.payment)
LNbits.utils.exportCSV(
this.paymentsCSV.columns,
payments,
this.wallet.name + '-payments'
)
})
},
formatCurrency: function (amount, currency) {
try {
return LNbits.utils.formatCurrency(amount, currency)
} catch (e) {
console.error(e)
return `${amount} ???`
}
}
},
watch: {
lazy: function (newVal) {
if (newVal === true) this.fetchPayments()
},
update: function () {
this.fetchPayments()
}
},
created: function () {
if (this.lazy === undefined) this.fetchPayments()
},
template: `
<q-card
:style="$q.screen.lt.md ? {
background: $q.screen.lt.md ? 'none !important': ''
, boxShadow: $q.screen.lt.md ? 'none !important': ''
, marginTop: $q.screen.lt.md ? '0px !important': ''
} : ''"
>
<q-card-section>
<div class="row items-center no-wrap q-mb-sm">
<div class="col">
<h5
class="text-subtitle1 q-my-none"
:v-text="$t('transactions')"
></h5>
</div>
<div class="gt-sm col-auto">
<q-btn flat color="grey" @click="exportCSV" :label="$t('export_csv')" ></q-btn>
<payment-chart :wallet="wallet" />
</div>
</div>
<q-input
:style="$q.screen.lt.md ? {
display: mobileSimple ? 'none !important': ''
} : ''"
filled
dense
clearable
v-model="paymentsTable.search"
debounce="300"
:placeholder="$t('search_by_tag_memo_amount')"
class="q-mb-md"
>
</q-input>
<q-table
dense
flat
:data="paymentsOmitter"
:row-key="paymentTableRowKey"
:columns="paymentsTable.columns"
:pagination.sync="paymentsTable.pagination"
:no-data-label="$t('no_transactions')"
:filter="paymentsTable.search"
:loading="paymentsTable.loading"
:hide-header="mobileSimple"
:hide-bottom="mobileSimple"
@request="fetchPayments"
>
<template v-slot:header="props">
<q-tr :props="props">
<q-th auto-width></q-th>
<q-th
v-for="col in props.cols"
:key="col.name"
:props="props"
v-text="col.label"
></q-th>
</q-tr>
</template>
<template v-slot:body="props">
<q-tr :props="props">
<q-td auto-width class="text-center">
<q-icon
v-if="props.row.isPaid"
size="14px"
:name="props.row.isOut ? 'call_made' : 'call_received'"
:color="props.row.isOut ? 'pink' : 'green'"
@click="props.expand = !props.expand"
></q-icon>
<q-icon
v-else
name="settings_ethernet"
color="grey"
@click="props.expand = !props.expand"
>
<q-tooltip
><span v-text="$t('pending')"></span
></q-tooltip>
</q-icon>
</q-td>
<q-td
key="time"
:props="props"
style="white-space: normal; word-break: break-all"
>
<q-badge
v-if="props.row.tag"
color="yellow"
text-color="black"
>
<a
v-text="'#'+props.row.tag"
class="inherit"
:href="['/', props.row.tag].join('')"
></a>
</q-badge>
<span v-text="props.row.memo"></span>
<br />
<i>
<span v-text="props.row.dateFrom"></span>
<q-tooltip
><span v-text="props.row.date"></span
></q-tooltip>
</i>
</q-td>
<q-td
auto-width
key="amount"
v-if="denomination != 'sats'"
:props="props"
class="col1"
v-text="parseFloat(String(props.row.fsat).replaceAll(',', '')) / 100"
>
</q-td>
<q-td class="col2" auto-width key="amount" v-else :props="props">
<span v-text="props.row.fsat"></span>
<br />
<i v-if="props.row.extra.wallet_fiat_currency">
<span
v-text="formatCurrency(props.row.extra.wallet_fiat_amount, props.row.extra.wallet_fiat_currency)"
></span>
<br />
</i>
<i v-if="props.row.extra.fiat_currency">
<span
v-text="formatCurrency(props.row.extra.fiat_amount, props.row.extra.fiat_currency)"
></span>
</i>
</q-td>
<q-dialog v-model="props.expand" :props="props" position="top">
<q-card class="q-pa-lg q-pt-xl lnbits__dialog-card">
<div class="text-center q-mb-lg">
<div v-if="props.row.isIn && props.row.pending">
<q-icon name="settings_ethernet" color="grey"></q-icon>
<span v-text="$t('invoice_waiting')"></span>
<lnbits-payment-details
:payment="props.row"
></lnbits-payment-details>
<div
v-if="props.row.bolt11"
class="text-center q-mb-lg"
>
<a :href="'lightning:' + props.row.bolt11">
<q-responsive :ratio="1" class="q-mx-xl">
<lnbits-qrcode
:value="'lightning:' + props.row.bolt11.toUpperCase()"
></lnbits-qrcode>
</q-responsive>
</a>
</div>
<div class="row q-mt-lg">
<q-btn
outline
color="grey"
@click="copyText(props.row.bolt11)"
:label="$t('copy_invoice')"
></q-btn>
<q-btn
v-close-popup
flat
color="grey"
class="q-ml-auto"
:label="$t('close')"
></q-btn>
</div>
</div>
<div v-else-if="props.row.isPaid && props.row.isIn">
<q-icon
size="18px"
:name="'call_received'"
:color="'green'"
></q-icon>
<span v-text="$t('payment_received')"></span>
<lnbits-payment-details
:payment="props.row"
></lnbits-payment-details>
</div>
<div v-else-if="props.row.isPaid && props.row.isOut">
<q-icon
size="18px"
:name="'call_made'"
:color="'pink'"
></q-icon>
<span v-text="$t('payment_sent')"></span>
<lnbits-payment-details
:payment="props.row"
></lnbits-payment-details>
</div>
<div v-else-if="props.row.isOut && props.row.pending">
<q-icon name="settings_ethernet" color="grey"></q-icon>
<span v-text="$t('outgoing_payment_pending')"></span>
<lnbits-payment-details
:payment="props.row"
></lnbits-payment-details>
</div>
</div>
</q-card>
</q-dialog>
</q-tr>
</template>
</q-table>
</q-card-section>
</q-card>
`
})
+384
View File
@@ -0,0 +1,384 @@
new Vue({
el: '#vue',
mixins: [windowMixin],
data: function () {
return {
isSuperUser: false,
activeWallet: {},
wallet: {},
cancel: {},
users: [],
wallets: [],
paymentDialog: {
show: false
},
walletDialog: {
show: false
},
topupDialog: {
show: false
},
createUserDialog: {
data: {},
fields: [
{
description: 'Username',
name: 'username'
},
{
description: 'Email',
name: 'email'
},
{
type: 'password',
description: 'Password',
name: 'password'
}
],
show: false
},
createWalletDialog: {
data: {},
fields: [
{
type: 'str',
description: 'Wallet Name',
name: 'name'
},
{
type: 'select',
values: ['', 'EUR', 'USD'],
description: 'Currency',
name: 'currency'
},
{
type: 'str',
description: 'Balance',
name: 'balance'
}
],
show: false
},
walletTable: {
columns: [
{
name: 'name',
align: 'left',
label: 'Name',
field: 'name'
},
{
name: 'currency',
align: 'left',
label: 'Currency',
field: 'currency'
},
{
name: 'balance_msat',
align: 'left',
label: 'Balance',
field: 'balance_msat'
},
{
name: 'deleted',
align: 'left',
label: 'Deleted',
field: 'deleted'
}
]
},
usersTable: {
columns: [
{
name: 'balance_msat',
align: 'left',
label: 'Balance',
field: 'balance_msat',
sortable: true
},
{
name: 'wallet_count',
align: 'left',
label: 'Wallet Count',
field: 'wallet_count',
sortable: true
},
{
name: 'transaction_count',
align: 'left',
label: 'Transaction Count',
field: 'transaction_count',
sortable: true
},
{
name: 'username',
align: 'left',
label: 'Username',
field: 'username',
sortable: true
},
{
name: 'email',
align: 'left',
label: 'Email',
field: 'email',
sortable: true
},
{
name: 'last_payment',
align: 'left',
label: 'Last Payment',
field: 'last_payment',
sortable: true
}
],
pagination: {
sortBy: 'balance_msat',
rowsPerPage: 10,
page: 1,
descending: true,
rowsNumber: 10
},
search: null,
hideEmpty: true,
loading: false
}
}
},
watch: {
'usersTable.hideEmpty': function (newVal, _) {
if (newVal) {
this.usersTable.filter = {
'transaction_count[gt]': 0
}
} else {
this.usersTable.filter = {}
}
this.fetchUsers()
}
},
created() {
this.fetchUsers()
},
mounted() {
this.chart1 = new Chart(this.$refs.chart1.getContext('2d'), {
type: 'bubble',
options: {
layout: {
padding: 10
}
},
data: {
datasets: [
{
label: 'Balance - TX Count in million sats',
backgroundColor: 'rgb(255, 99, 132)',
data: []
}
]
}
})
},
methods: {
formatSat: function (value) {
return LNbits.utils.formatSat(Math.floor(value / 1000))
},
usersTableRowKey: function (row) {
return row.id
},
createUser() {
LNbits.api
.request('POST', '/users/api/v1/user', null, this.createUserDialog.data)
.then(() => {
this.fetchUsers()
this.$q.notify({
type: 'positive',
message: 'Success! User created!',
icon: null
})
})
.catch(function (error) {
LNbits.utils.notifyApiError(error)
})
},
createWallet(user_id) {
LNbits.api
.request(
'POST',
`/users/api/v1/user/${user_id}/wallet`,
null,
this.createWalletDialog.data
)
.then(() => {
this.fetchUsers()
this.$q.notify({
type: 'positive',
message: 'Success! User created!',
icon: null
})
})
.catch(function (error) {
LNbits.utils.notifyApiError(error)
})
},
deleteUser(user_id) {
LNbits.utils
.confirmDialog('Are you sure you want to delete this user?')
.onOk(() => {
LNbits.api
.request('DELETE', `/users/api/v1/user/${user_id}`)
.then(() => {
this.fetchUsers()
this.$q.notify({
type: 'positive',
message: 'Success! User deleted!',
icon: null
})
})
.catch(function (error) {
LNbits.utils.notifyApiError(error)
})
})
},
undeleteUserWallet(user_id, wallet) {
LNbits.api
.request(
'GET',
`/users/api/v1/user/${user_id}/wallet/${wallet}/undelete`
)
.then(() => {
this.fetchWallets(user_id)
this.$q.notify({
type: 'positive',
message: 'Success! Undeleted user wallet!',
icon: null
})
})
.catch(function (error) {
LNbits.utils.notifyApiError(error)
})
},
deleteUserWallet(user_id, wallet, deleted) {
const dialogText = deleted
? '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(dialogText).onOk(() => {
LNbits.api
.request('DELETE', `/users/api/v1/user/${user_id}/wallet/${wallet}`)
.then(() => {
this.fetchWallets(user_id)
this.$q.notify({
type: 'positive',
message: 'Success! User wallet deleted!',
icon: null
})
})
.catch(function (error) {
LNbits.utils.notifyApiError(error)
})
})
},
updateChart(users) {
const filtered = users.filter(user => {
if (
user.balance_msat === null ||
user.balance_msat === 0 ||
user.wallet_count === 0
) {
return false
}
return true
})
const data = filtered.map(user => {
return {
x: user.transaction_count,
y: user.balance_msat / 1000000000,
r: 3
}
})
this.chart1.data.datasets[0].data = data
this.chart1.update()
},
fetchUsers(props) {
const params = LNbits.utils.prepareFilterQuery(this.usersTable, props)
LNbits.api
.request('GET', `/users/api/v1/user?${params}`)
.then(res => {
this.usersTable.loading = false
this.usersTable.pagination.rowsNumber = res.data.total
this.users = res.data.data
this.updateChart(this.users)
})
.catch(function (error) {
LNbits.utils.notifyApiError(error)
})
},
fetchWallets(user_id) {
LNbits.api
.request('GET', `/users/api/v1/user/${user_id}/wallet`)
.then(res => {
this.wallets = res.data
this.walletDialog.show = this.wallets.length > 0
if (!this.walletDialog.show) {
this.fetchUsers()
}
})
.catch(function (error) {
LNbits.utils.notifyApiError(error)
})
},
showPayments(wallet_id) {
this.activeWallet = this.wallets.find(wallet => wallet.id === wallet_id)
this.paymentDialog.show = true
},
toggleAdmin(user_id) {
LNbits.api
.request('GET', `/users/api/v1/user/${user_id}/admin`)
.then(() => {
this.fetchUsers()
this.$q.notify({
type: 'positive',
message: 'Success! Toggled admin!',
icon: null
})
})
.catch(function (error) {
LNbits.utils.notifyApiError(error)
})
},
exportUsers() {
console.log('export users')
},
topupCallback(res) {
if (res.success) {
this.wallets.forEach(wallet => {
if (res.wallet_id === wallet.id) {
wallet.balance_msat += res.credit * 1000
}
})
this.fetchUsers()
}
},
topupWallet() {
LNbits.api
.request(
'PUT',
'/users/api/v1/topup',
this.g.user.wallets[0].adminkey,
this.wallet
)
.then(_ => {
this.$q.notify({
type: 'positive',
message: `Success! Added ${this.wallet.amount} to ${this.wallet.id}`,
icon: null
})
this.wallet = {}
})
.catch(function (error) {
LNbits.utils.notifyApiError(error)
})
}
}
})
+21 -297
View File
@@ -1,95 +1,14 @@
/* globals windowMixin, decode, Vue, VueQrcodeReader, VueQrcode, Quasar, LNbits, _, EventHub, Chart, decryptLnurlPayAES */ /* globals windowMixin, decode, Vue, VueQrcodeReader, VueQrcode, Quasar, LNbits, _, EventHub, decryptLnurlPayAES */
Vue.component(VueQrcode.name, VueQrcode) Vue.component(VueQrcode.name, VueQrcode)
Vue.use(VueQrcodeReader) Vue.use(VueQrcodeReader)
function generateChart(canvas, rawData) {
const data = rawData.reduce(
(previous, current) => {
previous.labels.push(current.date)
previous.income.push(current.income)
previous.spending.push(current.spending)
previous.cumulative.push(current.balance)
return previous
},
{
labels: [],
income: [],
spending: [],
cumulative: []
}
)
return new Chart(canvas.getContext('2d'), {
type: 'bar',
data: {
labels: data.labels,
datasets: [
{
data: data.cumulative,
type: 'line',
label: 'balance',
backgroundColor: '#673ab7', // deep-purple
borderColor: '#673ab7',
borderWidth: 4,
pointRadius: 3,
fill: false
},
{
data: data.income,
type: 'bar',
label: 'in',
barPercentage: 0.75,
backgroundColor: window.Color('rgb(76,175,80)').alpha(0.5).rgbString() // green
},
{
data: data.spending,
type: 'bar',
label: 'out',
barPercentage: 0.75,
backgroundColor: window.Color('rgb(233,30,99)').alpha(0.5).rgbString() // pink
}
]
},
options: {
title: {
text: 'Chart.js Combo Time Scale'
},
tooltips: {
mode: 'index',
intersect: false
},
scales: {
xAxes: [
{
type: 'time',
display: true,
//offset: true,
time: {
minUnit: 'hour',
stepSize: 3
}
}
]
},
// performance tweaks
animation: {
duration: 0
},
elements: {
line: {
tension: 0
}
}
}
})
}
new Vue({ new Vue({
el: '#vue', el: '#vue',
mixins: [windowMixin], mixins: [windowMixin],
data: function () { data: function () {
return { return {
updatePayments: false,
origin: window.location.origin, origin: window.location.origin,
user: LNbits.map.user(window.user), user: LNbits.map.user(window.user),
receive: { receive: {
@@ -126,123 +45,11 @@ new Vue({
camera: 'auto' camera: 'auto'
} }
}, },
payments: [],
paymentsTable: {
columns: [
{
name: 'time',
align: 'left',
label: this.$t('memo') + '/' + this.$t('date'),
field: 'date',
sortable: true
},
{
name: 'amount',
align: 'right',
label: this.$t('amount') + ' (' + LNBITS_DENOMINATION + ')',
field: 'sat',
sortable: true
}
],
pagination: {
rowsPerPage: 10,
page: 1,
sortBy: 'time',
descending: true,
rowsNumber: 10
},
search: null,
loading: false
},
paymentsCSV: {
columns: [
{
name: 'pending',
align: 'left',
label: 'Pending',
field: 'pending'
},
{
name: 'memo',
align: 'left',
label: this.$t('memo'),
field: 'memo'
},
{
name: 'time',
align: 'left',
label: this.$t('date'),
field: 'date',
sortable: true
},
{
name: 'amount',
align: 'right',
label: this.$t('amount') + ' (' + LNBITS_DENOMINATION + ')',
field: 'sat',
sortable: true
},
{
name: 'fee',
align: 'right',
label: this.$t('fee') + ' (m' + LNBITS_DENOMINATION + ')',
field: 'fee'
},
{
name: 'tag',
align: 'right',
label: this.$t('tag'),
field: 'tag'
},
{
name: 'payment_hash',
align: 'right',
label: this.$t('payment_hash'),
field: 'payment_hash'
},
{
name: 'payment_proof',
align: 'right',
label: this.$t('payment_proof'),
field: 'payment_proof'
},
{
name: 'webhook',
align: 'right',
label: this.$t('webhook'),
field: 'webhook'
},
{
name: 'fiat_currency',
align: 'right',
label: 'Fiat Currency',
field: row => row.extra.wallet_fiat_currency
},
{
name: 'fiat_amount',
align: 'right',
label: 'Fiat Amount',
field: row => row.extra.wallet_fiat_amount
}
],
filter: null,
loading: false
},
paymentsChart: {
show: false,
group: {value: 'hour', label: 'Hour'},
groupOptions: [
{value: 'month', label: 'Month'},
{value: 'day', label: 'Day'},
{value: 'hour', label: 'Hour'}
],
instance: null
},
disclaimerDialog: { disclaimerDialog: {
show: false, show: false,
location: window.location location: window.location
}, },
balance: 0, balance: parseInt(wallet.balance_msat / 1000),
fiatBalance: 0, fiatBalance: 0,
mobileSimple: false, mobileSimple: false,
credit: 0, credit: 0,
@@ -268,63 +75,21 @@ new Vue({
) )
} }
}, },
filteredPayments: function () {
var q = this.paymentsTable.search
if (!q || q === '') return this.payments
return LNbits.utils.search(this.payments, q)
},
paymentsOmitter() {
if (this.$q.screen.lt.md && this.mobileSimple) {
return this.payments.length > 0 ? [this.payments[0]] : []
}
return this.payments
},
canPay: function () { canPay: function () {
if (!this.parse.invoice) return false if (!this.parse.invoice) return false
return this.parse.invoice.sat <= this.balance return this.parse.invoice.sat <= this.balance
},
pendingPaymentsExist: function () {
return this.payments.findIndex(payment => payment.pending) !== -1
} }
}, },
methods: { methods: {
msatoshiFormat: function (value) { msatoshiFormat: function (value) {
return LNbits.utils.formatSat(value / 1000) return LNbits.utils.formatSat(value / 1000)
}, },
paymentTableRowKey: function (row) {
return row.payment_hash + row.amount
},
closeCamera: function () { closeCamera: function () {
this.parse.camera.show = false this.parse.camera.show = false
}, },
showCamera: function () { showCamera: function () {
this.parse.camera.show = true this.parse.camera.show = true
}, },
showChart: function () {
this.paymentsChart.show = true
LNbits.api
.request(
'GET',
'/api/v1/payments/history?group=' + this.paymentsChart.group.value,
this.g.wallet.adminkey
)
.then(response => {
this.$nextTick(() => {
if (this.paymentsChart.instance) {
this.paymentsChart.instance.destroy()
}
this.paymentsChart.instance = generateChart(
this.$refs.canvas,
response.data
)
})
})
.catch(err => {
LNbits.utils.notifyApiError(err)
this.paymentsChart.show = false
})
},
focusInput(el) { focusInput(el) {
this.$nextTick(() => this.$refs[el].focus()) this.$nextTick(() => this.$refs[el].focus())
}, },
@@ -359,8 +124,7 @@ new Vue({
}, 10000) }, 10000)
}, },
onPaymentReceived: function (paymentHash) { onPaymentReceived: function (paymentHash) {
this.fetchPayments() this.updatePayments = !this.updatePayments
if (this.receive.paymentHash === paymentHash) { if (this.receive.paymentHash === paymentHash) {
this.receive.show = false this.receive.show = false
this.receive.paymentHash = null this.receive.paymentHash = null
@@ -407,8 +171,9 @@ new Vue({
}) })
} }
} }
})
this.fetchPayments() .then(() => {
this.updatePayments = !this.updatePayments
}) })
.catch(err => { .catch(err => {
LNbits.utils.notifyApiError(err) LNbits.utils.notifyApiError(err)
@@ -584,10 +349,10 @@ new Vue({
.getPayment(this.g.wallet, response.data.payment_hash) .getPayment(this.g.wallet, response.data.payment_hash)
.then(res => { .then(res => {
if (res.data.paid) { if (res.data.paid) {
this.parse.show = false
clearInterval(this.parse.paymentChecker)
dismissPaymentMsg() dismissPaymentMsg()
this.fetchPayments() clearInterval(this.parse.paymentChecker)
this.updatePayments = !this.updatePayments
this.parse.show = false
} }
}) })
}, 2000) }, 2000)
@@ -595,6 +360,8 @@ new Vue({
.catch(err => { .catch(err => {
dismissPaymentMsg() dismissPaymentMsg()
LNbits.utils.notifyApiError(err) LNbits.utils.notifyApiError(err)
this.updatePayments = !this.updatePayments
this.parse.show = false
}) })
}, },
payLnurl: function () { payLnurl: function () {
@@ -627,7 +394,6 @@ new Vue({
if (res.data.paid) { if (res.data.paid) {
dismissPaymentMsg() dismissPaymentMsg()
clearInterval(this.parse.paymentChecker) clearInterval(this.parse.paymentChecker)
this.fetchPayments()
// show lnurlpay success action // show lnurlpay success action
if (response.data.success_action) { if (response.data.success_action) {
switch (response.data.success_action.tag) { switch (response.data.success_action.tag) {
@@ -740,27 +506,10 @@ new Vue({
}) })
}) })
.catch(err => { .catch(err => {
this.paymentsTable.loading = false
LNbits.utils.notifyApiError(err) LNbits.utils.notifyApiError(err)
}) })
}) })
}, },
fetchPayments: function (props) {
const params = LNbits.utils.prepareFilterQuery(this.paymentsTable, props)
return LNbits.api
.getPayments(this.g.wallet, params)
.then(response => {
this.paymentsTable.loading = false
this.paymentsTable.pagination.rowsNumber = response.data.total
this.payments = response.data.data.map(obj => {
return LNbits.map.payment(obj)
})
})
.catch(err => {
this.paymentsTable.loading = false
LNbits.utils.notifyApiError(err)
})
},
fetchBalance: function () { fetchBalance: function () {
LNbits.api.getWallet(this.g.wallet).then(response => { LNbits.api.getWallet(this.g.wallet).then(response => {
this.balance = Math.floor(response.data.balance / 1000) this.balance = Math.floor(response.data.balance / 1000)
@@ -785,30 +534,10 @@ new Vue({
}) })
.catch(e => console.error(e)) .catch(e => console.error(e))
}, },
formatFiat(currency, amount) {
return LNbits.utils.formatCurrency(amount, currency)
},
updateBalanceCallback: function (res) { updateBalanceCallback: function (res) {
this.balance += res.value if (res.success && wallet.id === res.wallet_id) {
}, this.balance += res.credit
exportCSV: function () {
// status is important for export but it is not in paymentsTable
// because it is manually added with payment detail link and icons
// and would cause duplication in the list
const pagination = this.paymentsTable.pagination
const query = {
sortby: pagination.sortBy ?? 'time',
direction: pagination.descending ? 'desc' : 'asc'
} }
const params = new URLSearchParams(query)
LNbits.api.getPayments(this.g.wallet, params).then(response => {
const payments = response.data.data.map(LNbits.map.payment)
LNbits.utils.exportCSV(
this.paymentsCSV.columns,
payments,
this.g.wallet.name + '-payments'
)
})
}, },
pasteToTextArea: function () { pasteToTextArea: function () {
this.$refs.textArea.focus() // Set cursor to textarea this.$refs.textArea.focus() // Set cursor to textarea
@@ -817,14 +546,6 @@ new Vue({
}) })
} }
}, },
watch: {
payments: function () {
this.fetchBalance()
},
'paymentsChart.group': function () {
this.showChart()
}
},
created: function () { created: function () {
let urlParams = new URLSearchParams(window.location.search) let urlParams = new URLSearchParams(window.location.search)
if (urlParams.has('lightning') || urlParams.has('lnurl')) { if (urlParams.has('lightning') || urlParams.has('lnurl')) {
@@ -836,12 +557,15 @@ new Vue({
if (this.$q.screen.lt.md) { if (this.$q.screen.lt.md) {
this.mobileSimple = true this.mobileSimple = true
} }
this.fetchPayments()
this.update.name = this.g.wallet.name this.update.name = this.g.wallet.name
this.update.currency = this.g.wallet.currency this.update.currency = this.g.wallet.currency
this.receive.units = ['sat', ...window.currencies] this.receive.units = ['sat', ...window.currencies]
}, },
watch: {
updatePayments: function () {
this.fetchBalance()
}
},
mounted: function () { mounted: function () {
// show disclaimer // show disclaimer
if (!this.$q.localStorage.getItem('lnbits.disclaimerShown')) { if (!this.$q.localStorage.getItem('lnbits.disclaimerShown')) {
@@ -849,9 +573,9 @@ new Vue({
this.$q.localStorage.set('lnbits.disclaimerShown', true) this.$q.localStorage.set('lnbits.disclaimerShown', true)
} }
// listen to incoming payments // listen to incoming payments
LNbits.events.onInvoicePaid(this.g.wallet, payment => LNbits.events.onInvoicePaid(this.g.wallet, payment => {
this.onPaymentReceived(payment.payment_hash) this.onPaymentReceived(payment.payment_hash)
) })
eventReactionWebocket(wallet.id) eventReactionWebocket(wallet.id)
} }
}) })

Some files were not shown because too many files have changed in this diff Show More