chore: use prettier for all of the codebase (#2466)

* chore: use prettier for all of the codebase
we only checked `lnbits` dir before
This commit is contained in:
dni ⚡ 2024-04-25 11:13:08 +02:00 committed by GitHub
parent f5293ca645
commit 4a0fb59461
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 5064 additions and 5026 deletions

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

View file

@ -9,7 +9,7 @@ check: mypy pyright checkblack checkruff checkprettier checkbundle
test: test-unit test-wallets test-api test-regtest 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
@ -27,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 .

View file

@ -1,4 +1,3 @@
<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">
@ -8,7 +7,9 @@
![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.
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 the community chat.
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:

View file

@ -5,8 +5,6 @@ title: API reference
nav_order: 3 nav_order: 3
--- ---
# API reference
API reference
=============
[Swagger Docs](https://legend.lnbits.com/docs) [Swagger Docs](https://legend.lnbits.com/docs)

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
``` ```

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;'"
``` ```

View file

@ -2,25 +2,28 @@
<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
rel="stylesheet"
type="text/css"
href="https://unpkg.com/swagger-ui-dist@3/swagger-ui.css"
/>
<title>My New API</title> <title>My New API</title>
</head> </head>
<body> <body>
<div id="swagger-ui"></div> <!-- Div to hold the UI component --> <div id="swagger-ui"></div>
<!-- Div to hold the UI component -->
<script> <script>
window.onload = function () { window.onload = function () {
// Begin Swagger UI call region // Begin Swagger UI call region
const ui = SwaggerUIBundle({ const ui = SwaggerUIBundle({
url: "https://legend.lnbits.com/openapi.json", //Location of Open API spec in the repo url: 'https://legend.lnbits.com/openapi.json', //Location of Open API spec in the repo
dom_id: '#swagger-ui', dom_id: '#swagger-ui',
deepLinking: true, deepLinking: true,
presets: [ presets: [
SwaggerUIBundle.presets.apis, SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset SwaggerUIBundle.SwaggerUIStandalonePreset
], ],
plugins: [ plugins: [SwaggerUIBundle.plugins.DownloadUrl]
SwaggerUIBundle.plugins.DownloadUrl
],
}) })
window.ui = ui window.ui = ui
} }

View file

@ -5,15 +5,12 @@ 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://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")`.
Example vue-js function for listening to the websocket: Example vue-js function for listening to the websocket:
``` ```

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-legend
$ 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.

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,7 +77,9 @@ 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",
@ -97,7 +99,7 @@ It goes under the `extensions` object and it is of the form:
<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. |
@ -109,13 +111,14 @@ 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
@ -127,7 +130,7 @@ It goes under the `repos` object and it is of the form:
``` ```
| 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`) |
@ -135,5 +138,3 @@ It goes under the `repos` object and it is of the form:
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)

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>
@ -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>

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

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
``` ```
@ -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
@ -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.
@ -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
``` ```

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**

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...

View file

@ -2124,9 +2124,7 @@
} }
}, },
"response_type": "__aiter__", "response_type": "__aiter__",
"response": [ "response": [{}]
{}
]
} }
} }
}, },