Merge branch 'umbrel-works' of https://github.com/shocknet/Lightning.Pub into umbrel-works
This commit is contained in:
commit
6e4a01cc51
46 changed files with 6120 additions and 4651 deletions
34
.github/workflows/push.yml
vendored
34
.github/workflows/push.yml
vendored
|
|
@ -1,9 +1,9 @@
|
||||||
|
|
||||||
name: Create and publish a Docker image
|
name: Create and publish a Docker image
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
release:
|
||||||
branches: ['umbrel-works']
|
types: [created, published, prereleased]
|
||||||
|
workflow_dispatch: # This allows manual triggering of the workflow
|
||||||
|
|
||||||
env:
|
env:
|
||||||
REGISTRY: ghcr.io
|
REGISTRY: ghcr.io
|
||||||
|
|
@ -15,15 +15,15 @@ jobs:
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
packages: write
|
packages: write
|
||||||
attestations: write
|
|
||||||
id-token: write
|
id-token: write
|
||||||
|
security-events: write
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Log in to the Container registry
|
- name: Log in to the Container registry
|
||||||
uses: docker/login-action@65b78e6e13532edd9afa3aa52ac7964289d1a9c1
|
uses: docker/login-action@v2
|
||||||
with:
|
with:
|
||||||
registry: ${{ env.REGISTRY }}
|
registry: ${{ env.REGISTRY }}
|
||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
|
|
@ -31,17 +31,33 @@ jobs:
|
||||||
|
|
||||||
- name: Extract metadata (tags, labels) for Docker
|
- name: Extract metadata (tags, labels) for Docker
|
||||||
id: meta
|
id: meta
|
||||||
uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7
|
uses: docker/metadata-action@v4
|
||||||
with:
|
with:
|
||||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||||
|
|
||||||
- name: Build and push Docker image
|
- name: Build and push Docker image
|
||||||
id: push
|
id: build-and-push
|
||||||
uses: docker/build-push-action@f2a1d5e99d037542a71f64918e516c093c6f3fc4
|
uses: docker/build-push-action@v4
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
|
file: ./Dockerfile
|
||||||
push: true
|
push: true
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
tags: ghcr.io/${{ github.repository_owner }}/lightning-pub:latest
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
|
||||||
|
- name: Capture image digest
|
||||||
|
id: capture-digest
|
||||||
|
run: |
|
||||||
|
DIGEST=$(docker inspect --format='{{index .RepoDigests 0}}' ghcr.io/${{ github.repository_owner }}/lightning-pub:latest | cut -d'@' -f2)
|
||||||
|
echo "Raw Digest is $DIGEST"
|
||||||
|
echo "::set-output name=digest::$DIGEST"
|
||||||
|
|
||||||
|
- name: Debug Print Digest
|
||||||
|
run: echo "Digest is ${{ steps.capture-digest.outputs.digest }}"
|
||||||
|
|
||||||
|
- name: Attest build provenance
|
||||||
|
uses: actions/attest-build-provenance@v1
|
||||||
|
with:
|
||||||
|
subject-digest: ${{ steps.capture-digest.outputs.digest }}
|
||||||
|
subject-name: ghcr.io/${{ github.repository_owner }}/lightning-pub:latest
|
||||||
|
github-token: ${{ secrets.PAT_TOKEN }}
|
||||||
|
|
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -10,3 +10,4 @@ db.sqlite
|
||||||
metrics.sqlite
|
metrics.sqlite
|
||||||
.key/
|
.key/
|
||||||
logs
|
logs
|
||||||
|
.jwt_secret
|
||||||
661
LICENSE
Normal file
661
LICENSE
Normal file
|
|
@ -0,0 +1,661 @@
|
||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
37
README.md
37
README.md
|
|
@ -10,13 +10,17 @@
|
||||||
|
|
||||||
"Pub" is a [Nostr](https://nostr.info)-native account system designed to make running Lightning infrastructure for your friends/family/customers easier than previously thought possible.
|
"Pub" is a [Nostr](https://nostr.info)-native account system designed to make running Lightning infrastructure for your friends/family/customers easier than previously thought possible.
|
||||||
|
|
||||||
It may come as a surprise that the biggest hurdle to more Uncle Jim nodes hasn't been with Bitcoin/Lightning node management itself, since even in bad patterns like mobile nodes, that is easily automated.
|
It may come as a surprise that the biggest hurdle to more Uncle Jim nodes hasn't been with Bitcoin/Lightning node management itself, as we've seen liquidity easily automated even in unreliable environments like mobile nodes.
|
||||||
|
|
||||||
It's the legacy baggage of traditional web infrastructure, things like IP4, reverse proxies, DNS, Firewalls and SSL certificates, all of which require a personal configuration that is a hurdle for most. The slow and unreliable nature of things like Tor have proven to be dead-ends, and Bolt12 being a re-implementation of Tor is destined for the same fate.
|
It's the legacy baggage of traditional Client-Server web infrastructure, things like IP4, Reverse Proxies, DNS, Firewalls and SSL certificates, all of which require a personal configuration that is a hurdle for most.
|
||||||
|
|
||||||
Pub solves these network challenges with a Full RPC that is Nostr-native. Being Nostr-native eliminates the complexity of legacy server configuration by using completely commoditized and trustless Nostr relays. Additionally, some optional services are integrated for backward compatibility with LNURL and Lightning Address.
|
Tor as a workaround has proven too slow and unreliable, and a dead-end for clearnet-web usecases. Bxlt12, being a re-implementation of Tor, appears destined for the same fate.
|
||||||
|
|
||||||
By solving the networking and programability hurdles, Pub's provide a 3rd Lightning Layer that enables node-runners and Uncle Jims to more easily bring their personal network into Bitcoin's permissionless economy. In doing so, Pub can keep the Lightning Network decentralized, with custodial scaling free of fiat rails, large banks, and other forms of high-time-preference shitcoinery.
|
Pub solves these challenges with a P2P-like design that is also web-friendly, by implementing a full RPC that is Nostr-native. Being Nostr-native eliminates the complexity of configuring your node like a server by using commodity Nostr relays. These relays, unlike LNURL proxies, are trustless by nature of Nostr's own encryption spec (NIP44).
|
||||||
|
|
||||||
|
Additionally, support for optional services are integrated into Pub for operators seeking backward compatibility with legacy LNURLs and Lightning Addresses.
|
||||||
|
|
||||||
|
By solving the networking and programability hurdles, Pub provides Lightning with a 3rd Layer that enables node-runners and Uncle Jims to more easily bring their personal network into Bitcoin's permissionless economy. In doing so, Pub runners can keep the Lightning Network decentralized, with custodial scaling that is free of fiat rails, large banks, and other forms of high-time-preference shitcoinery.
|
||||||
|
|
||||||
#### Features:
|
#### Features:
|
||||||
|
|
||||||
|
|
@ -27,21 +31,30 @@ By solving the networking and programability hurdles, Pub's provide a 3rd Lightn
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
- Connecting via ShockWallet is as easy as pasting an nprofile
|
||||||
|
- Or use a link to share your nprofile with friends and family
|
||||||
|
|
||||||
|
<img src="https://cdn.shockwallet.app/add_src_sm.png" height="20%" alt="Connect Wallet"> <img src="https://cdn.shockwallet.app/src_invite_sm.png" height="20%" alt="Invite Guests">
|
||||||
|
|
||||||
|
|
||||||
#### Planned
|
#### Planned
|
||||||
- [ ] Management Dashboard is actively being integrated into [ShockWallet](https://github.com/shocknet/wallet2)
|
- [ ] A management dashboard is actively being integrated into [ShockWallet](https://github.com/shocknet/wallet2)
|
||||||
- [ ] Nostr native "offers"
|
- [ ] Nostr native "offers" (successor to LNURL-Pay, Lightning Address, Bxlt12)
|
||||||
- [ ] Automated Channels
|
- [ ] Automated Channels
|
||||||
- [ ] Bootstrap Peering (Passive "LSP")
|
- [ ] Bootstrap Peering (Passive "LSP")
|
||||||
- [ ] Event Notifications
|
- [ ] Event Notifications
|
||||||
- [ ] Submarine Swaps
|
- [ ] Swap integration
|
||||||
- [ ] High-Availabilty / Clustering
|
- [ ] High-Availabilty / Clustering
|
||||||
|
|
||||||
Dashboard Wireframe:
|
Dashboard Wireframe:
|
||||||
|
|
||||||
<img src="https://shockwallet.b-cdn.net/pub_home_ss.png" alt="Pub Dashboard" width="240">
|
<img src="https://shockwallet.b-cdn.net/pub_home_ss.png" alt="Pub Dashboard" width="240">
|
||||||
|
|
||||||
> [!IMPORTANT]
|
> [!IMPORTANT]
|
||||||
> ShockWallet and Lightning.Pub are free software. If you would like to see continued development, please show your [**support**](https://github.com/sponsors/shocknet) 😊
|
> ShockWallet and Lightning.Pub are free software. If you would like to see continued development, please show your [**support**](https://github.com/sponsors/shocknet) 😊<br>
|
||||||
|
|
||||||
|
<img src="https://www.gnu.org/graphics/agplv3-with-text-162x68.png" alt="License">
|
||||||
|
<br>
|
||||||
|
|
||||||
> [!WARNING]
|
> [!WARNING]
|
||||||
> While this software has been used in a high-profile production environment for over a year, it should still be considered bleeding edge. Special care has been taken to mitigate the risk of drainage attacks, which is a common risk to all Lightning API's. An integrated Watchdog service will terminate spends if it detects a discrepency between LND and the database, for this reason **IT IS NOT RECOMMENDED TO USE PUB ALONGSIDE OTHER ACCOUNT SYSTEMS**. While we give the utmost care and attention to security, **the internet is an adversarial environment and SECURITY/RELIABILITY ARE NOT GUARANTEED- USE AT YOUR OWN RISK**.
|
> While this software has been used in a high-profile production environment for over a year, it should still be considered bleeding edge. Special care has been taken to mitigate the risk of drainage attacks, which is a common risk to all Lightning API's. An integrated Watchdog service will terminate spends if it detects a discrepency between LND and the database, for this reason **IT IS NOT RECOMMENDED TO USE PUB ALONGSIDE OTHER ACCOUNT SYSTEMS**. While we give the utmost care and attention to security, **the internet is an adversarial environment and SECURITY/RELIABILITY ARE NOT GUARANTEED- USE AT YOUR OWN RISK**.
|
||||||
|
|
@ -54,11 +67,15 @@ Coming Soon
|
||||||
|
|
||||||
Coming Soon
|
Coming Soon
|
||||||
|
|
||||||
|
## Docker
|
||||||
|
|
||||||
|
`docker pull ghcr.io/shocknet/lightning-pub:latest`
|
||||||
|
|
||||||
## Manual CLI Installation
|
## Manual CLI Installation
|
||||||
|
|
||||||
#### Notes:
|
#### Notes:
|
||||||
* Use of a reverse proxy is only required if you wish to serve LNURLs
|
* Use of a reverse proxy is only required if you wish to serve LNURLs
|
||||||
* The service defaults to port `8080`
|
* The service defaults to port `1776`
|
||||||
* Requires [Node.js](https://nodejs.org) >=18.x
|
* Requires [Node.js](https://nodejs.org) >=18.x
|
||||||
* Commands for your specific OS may differ slightly, Ubuntu/Debian used for example
|
* Commands for your specific OS may differ slightly, Ubuntu/Debian used for example
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,13 +9,16 @@
|
||||||
#LND_CERT_PATH=~/.lnd/tls.cert
|
#LND_CERT_PATH=~/.lnd/tls.cert
|
||||||
#LND_MACAROON_PATH=~/.lnd/data/chain/bitcoin/mainnet/admin.macaroon
|
#LND_MACAROON_PATH=~/.lnd/data/chain/bitcoin/mainnet/admin.macaroon
|
||||||
|
|
||||||
|
LIQUIDITY_PROVIDER_PUB=
|
||||||
|
|
||||||
#DB
|
#DB
|
||||||
#DATABASE_FILE=db.sqlite
|
#DATABASE_FILE=db.sqlite
|
||||||
#METRICS_DATABASE_FILE=metrics.sqlite
|
#METRICS_DATABASE_FILE=metrics.sqlite
|
||||||
|
#LOGS_DIR=logs
|
||||||
|
|
||||||
#LOCALHOST
|
#LOCALHOST
|
||||||
#ADMIN_TOKEN=
|
#ADMIN_TOKEN=
|
||||||
#PORT=8080
|
#PORT=1776
|
||||||
#JWT_SECRET=
|
#JWT_SECRET=
|
||||||
|
|
||||||
#LIGHTNING
|
#LIGHTNING
|
||||||
|
|
@ -67,6 +70,7 @@
|
||||||
#MOCK_LND=false
|
#MOCK_LND=false
|
||||||
#ALLOW_BALANCE_MIGRATION=false
|
#ALLOW_BALANCE_MIGRATION=false
|
||||||
#MIGRATE_DB=false
|
#MIGRATE_DB=false
|
||||||
|
#LOG_LEVEL=DEBUG
|
||||||
|
|
||||||
#METRICS
|
#METRICS
|
||||||
#RECORD_PERFORMANCE=true
|
#RECORD_PERFORMANCE=true
|
||||||
|
|
|
||||||
|
|
@ -100,6 +100,11 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- This methods has an __empty__ __request__ body
|
- This methods has an __empty__ __request__ body
|
||||||
- output: [MigrationUpdate](#MigrationUpdate)
|
- output: [MigrationUpdate](#MigrationUpdate)
|
||||||
|
|
||||||
|
- GetHttpCreds
|
||||||
|
- auth type: __User__
|
||||||
|
- This methods has an __empty__ __request__ body
|
||||||
|
- output: [HttpCreds](#HttpCreds)
|
||||||
|
|
||||||
- BatchUser
|
- BatchUser
|
||||||
- auth type: __User__
|
- auth type: __User__
|
||||||
- This methods has an __empty__ __request__ body
|
- This methods has an __empty__ __request__ body
|
||||||
|
|
@ -115,9 +120,9 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
|
|
||||||
- __User__:
|
- __User__:
|
||||||
- expected context content
|
- expected context content
|
||||||
- __user_id__: _string_
|
|
||||||
- __app_id__: _string_
|
- __app_id__: _string_
|
||||||
- __app_user_id__: _string_
|
- __app_user_id__: _string_
|
||||||
|
- __user_id__: _string_
|
||||||
|
|
||||||
- __Admin__:
|
- __Admin__:
|
||||||
- expected context content
|
- expected context content
|
||||||
|
|
@ -458,6 +463,13 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- This methods has an __empty__ __request__ body
|
- This methods has an __empty__ __request__ body
|
||||||
- output: [MigrationUpdate](#MigrationUpdate)
|
- output: [MigrationUpdate](#MigrationUpdate)
|
||||||
|
|
||||||
|
- GetHttpCreds
|
||||||
|
- auth type: __User__
|
||||||
|
- http method: __post__
|
||||||
|
- http route: __/api/user/http_creds__
|
||||||
|
- This methods has an __empty__ __request__ body
|
||||||
|
- output: [HttpCreds](#HttpCreds)
|
||||||
|
|
||||||
- BatchUser
|
- BatchUser
|
||||||
- auth type: __User__
|
- auth type: __User__
|
||||||
- http method: __post__
|
- http method: __post__
|
||||||
|
|
@ -470,45 +482,41 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
## Messages
|
## Messages
|
||||||
### The content of requests and response from the methods
|
### The content of requests and response from the methods
|
||||||
|
|
||||||
### AddAppInvoiceRequest
|
### BanUserRequest
|
||||||
- __payer_identifier__: _string_
|
- __user_id__: _string_
|
||||||
- __http_callback_url__: _string_
|
|
||||||
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
|
|
||||||
|
|
||||||
### GetAppUserRequest
|
### SendAppUserToAppUserPaymentRequest
|
||||||
- __user_identifier__: _string_
|
- __from_user_identifier__: _string_
|
||||||
|
- __to_user_identifier__: _string_
|
||||||
|
- __amount__: _number_
|
||||||
|
|
||||||
### LnurlPayInfoResponse
|
### SendAppUserToAppPaymentRequest
|
||||||
- __tag__: _string_
|
- __from_user_identifier__: _string_
|
||||||
- __callback__: _string_
|
- __amount__: _number_
|
||||||
- __maxSendable__: _number_
|
|
||||||
- __minSendable__: _number_
|
|
||||||
- __metadata__: _string_
|
|
||||||
- __allowsNostr__: _boolean_
|
|
||||||
- __nostrPubkey__: _string_
|
|
||||||
|
|
||||||
### LinkNPubThroughTokenRequest
|
### GetUserOperationsRequest
|
||||||
- __token__: _string_
|
- __latestIncomingInvoice__: _number_
|
||||||
- __nostr_pub__: _string_
|
- __latestOutgoingInvoice__: _number_
|
||||||
|
- __latestIncomingTx__: _number_
|
||||||
|
- __latestOutgoingTx__: _number_
|
||||||
|
- __latestIncomingUserToUserPayment__: _number_
|
||||||
|
- __latestOutgoingUserToUserPayment__: _number_
|
||||||
|
- __max_size__: _number_
|
||||||
|
|
||||||
### NewInvoiceResponse
|
### GetUserOperationsResponse
|
||||||
- __invoice__: _string_
|
- __latestOutgoingInvoiceOperations__: _[UserOperations](#UserOperations)_
|
||||||
|
- __latestIncomingInvoiceOperations__: _[UserOperations](#UserOperations)_
|
||||||
|
- __latestOutgoingTxOperations__: _[UserOperations](#UserOperations)_
|
||||||
|
- __latestIncomingTxOperations__: _[UserOperations](#UserOperations)_
|
||||||
|
- __latestOutgoingUserToUserPayemnts__: _[UserOperations](#UserOperations)_
|
||||||
|
- __latestIncomingUserToUserPayemnts__: _[UserOperations](#UserOperations)_
|
||||||
|
|
||||||
### PayAddressRequest
|
### ClosureMigration
|
||||||
- __address__: _string_
|
- __closes_at_unix__: _number_
|
||||||
- __amoutSats__: _number_
|
|
||||||
- __satsPerVByte__: _number_
|
|
||||||
|
|
||||||
### GetProductBuyLinkResponse
|
### AuthAppRequest
|
||||||
- __link__: _string_
|
- __name__: _string_
|
||||||
|
- __allow_user_creation__: _boolean_ *this field is optional
|
||||||
### OpenChannel
|
|
||||||
- __channel_id__: _string_
|
|
||||||
- __capacity__: _number_
|
|
||||||
- __active__: _boolean_
|
|
||||||
- __lifetime__: _number_
|
|
||||||
- __local_balance__: _number_
|
|
||||||
- __remote_balance__: _number_
|
|
||||||
|
|
||||||
### Application
|
### Application
|
||||||
- __name__: _string_
|
- __name__: _string_
|
||||||
|
|
@ -516,17 +524,18 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- __balance__: _number_
|
- __balance__: _number_
|
||||||
- __npub__: _string_
|
- __npub__: _string_
|
||||||
|
|
||||||
### AuthApp
|
### AddAppInvoiceRequest
|
||||||
- __app__: _[Application](#Application)_
|
- __payer_identifier__: _string_
|
||||||
- __auth_token__: _string_
|
- __http_callback_url__: _string_
|
||||||
|
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
|
||||||
|
|
||||||
### PayAppUserInvoiceRequest
|
### GetAppUserLNURLInfoRequest
|
||||||
- __user_identifier__: _string_
|
- __user_identifier__: _string_
|
||||||
- __invoice__: _string_
|
- __base_url_override__: _string_
|
||||||
- __amount__: _number_
|
|
||||||
|
|
||||||
### OpenChannelResponse
|
### LnurlLinkResponse
|
||||||
- __channelId__: _string_
|
- __lnurl__: _string_
|
||||||
|
- __k1__: _string_
|
||||||
|
|
||||||
### LnurlWithdrawInfoResponse
|
### LnurlWithdrawInfoResponse
|
||||||
- __tag__: _string_
|
- __tag__: _string_
|
||||||
|
|
@ -538,44 +547,73 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- __balanceCheck__: _string_
|
- __balanceCheck__: _string_
|
||||||
- __payLink__: _string_
|
- __payLink__: _string_
|
||||||
|
|
||||||
### MigrationUpdate
|
### UserOperation
|
||||||
- __closure__: _[ClosureMigration](#ClosureMigration)_ *this field is optional
|
- __paidAtUnix__: _number_
|
||||||
- __relays__: _[RelaysMigration](#RelaysMigration)_ *this field is optional
|
- __type__: _[UserOperationType](#UserOperationType)_
|
||||||
|
- __inbound__: _boolean_
|
||||||
### BannedAppUser
|
|
||||||
- __app_name__: _string_
|
|
||||||
- __app_id__: _string_
|
|
||||||
- __user_identifier__: _string_
|
|
||||||
- __nostr_pub__: _string_
|
|
||||||
|
|
||||||
### AuthAppRequest
|
|
||||||
- __name__: _string_
|
|
||||||
- __allow_user_creation__: _boolean_ *this field is optional
|
|
||||||
|
|
||||||
### SendAppUserToAppUserPaymentRequest
|
|
||||||
- __from_user_identifier__: _string_
|
|
||||||
- __to_user_identifier__: _string_
|
|
||||||
- __amount__: _number_
|
- __amount__: _number_
|
||||||
|
- __identifier__: _string_
|
||||||
|
- __operationId__: _string_
|
||||||
|
- __service_fee__: _number_
|
||||||
|
- __network_fee__: _number_
|
||||||
|
- __confirmed__: _boolean_
|
||||||
|
- __tx_hash__: _string_
|
||||||
|
- __internal__: _boolean_
|
||||||
|
|
||||||
### NewAddressResponse
|
### RelaysMigration
|
||||||
- __address__: _string_
|
- __relays__: ARRAY of: _string_
|
||||||
|
|
||||||
### SetMockAppUserBalanceRequest
|
### RequestNPubLinkingTokenRequest
|
||||||
- __user_identifier__: _string_
|
- __user_identifier__: _string_
|
||||||
|
|
||||||
|
### EncryptionExchangeRequest
|
||||||
|
- __publicKey__: _string_
|
||||||
|
- __deviceId__: _string_
|
||||||
|
|
||||||
|
### AppsMetricsRequest
|
||||||
|
- __from_unix__: _number_ *this field is optional
|
||||||
|
- __to_unix__: _number_ *this field is optional
|
||||||
|
- __include_operations__: _boolean_ *this field is optional
|
||||||
|
|
||||||
|
### ClosedChannel
|
||||||
|
- __channel_id__: _string_
|
||||||
|
- __capacity__: _number_
|
||||||
|
- __closed_height__: _number_
|
||||||
|
|
||||||
|
### OpenChannelResponse
|
||||||
|
- __channelId__: _string_
|
||||||
|
|
||||||
|
### Product
|
||||||
|
- __id__: _string_
|
||||||
|
- __name__: _string_
|
||||||
|
- __price_sats__: _number_
|
||||||
|
|
||||||
|
### PayAppUserInvoiceRequest
|
||||||
|
- __user_identifier__: _string_
|
||||||
|
- __invoice__: _string_
|
||||||
- __amount__: _number_
|
- __amount__: _number_
|
||||||
|
|
||||||
### NewInvoiceRequest
|
### NewInvoiceRequest
|
||||||
- __amountSats__: _number_
|
- __amountSats__: _number_
|
||||||
- __memo__: _string_
|
- __memo__: _string_
|
||||||
|
|
||||||
### HandleLnurlPayResponse
|
### LiveUserOperation
|
||||||
- __pr__: _string_
|
- __operation__: _[UserOperation](#UserOperation)_
|
||||||
- __routes__: ARRAY of: _[Empty](#Empty)_
|
|
||||||
|
|
||||||
### ClosureMigration
|
### HttpCreds
|
||||||
- __closes_at_unix__: _number_
|
- __url__: _string_
|
||||||
|
- __token__: _string_
|
||||||
|
|
||||||
### Empty
|
### UsageMetric
|
||||||
|
- __processed_at_ms__: _number_
|
||||||
|
- __parsed_in_nano__: _number_
|
||||||
|
- __auth_in_nano__: _number_
|
||||||
|
- __validate_in_nano__: _number_
|
||||||
|
- __handle_in_nano__: _number_
|
||||||
|
- __rpc_name__: _string_
|
||||||
|
- __batch__: _boolean_
|
||||||
|
- __nostr__: _boolean_
|
||||||
|
- __batch_size__: _number_
|
||||||
|
|
||||||
### RoutingEvent
|
### RoutingEvent
|
||||||
- __incoming_channel_id__: _number_
|
- __incoming_channel_id__: _number_
|
||||||
|
|
@ -591,70 +629,20 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- __offchain__: _boolean_
|
- __offchain__: _boolean_
|
||||||
- __forward_fail_event__: _boolean_
|
- __forward_fail_event__: _boolean_
|
||||||
|
|
||||||
### ChannelRouting
|
### ChannelBalanceEvent
|
||||||
|
- __block_height__: _number_
|
||||||
- __channel_id__: _string_
|
- __channel_id__: _string_
|
||||||
- __send_errors__: _number_
|
- __local_balance_sats__: _number_
|
||||||
- __receive_errors__: _number_
|
- __remote_balance_sats__: _number_
|
||||||
- __forward_errors_as_input__: _number_
|
|
||||||
- __forward_errors_as_output__: _number_
|
|
||||||
- __missed_forward_fee_as_input__: _number_
|
|
||||||
- __missed_forward_fee_as_output__: _number_
|
|
||||||
- __forward_fee_as_input__: _number_
|
|
||||||
- __forward_fee_as_output__: _number_
|
|
||||||
- __events_number__: _number_
|
|
||||||
|
|
||||||
### BanUserResponse
|
### HandleLnurlPayResponse
|
||||||
- __balance_sats__: _number_
|
- __pr__: _string_
|
||||||
- __banned_app_users__: ARRAY of: _[BannedAppUser](#BannedAppUser)_
|
- __routes__: ARRAY of: _[Empty](#Empty)_
|
||||||
|
|
||||||
### UsageMetric
|
### UserOperations
|
||||||
- __processed_at_ms__: _number_
|
- __fromIndex__: _number_
|
||||||
- __parsed_in_nano__: _number_
|
- __toIndex__: _number_
|
||||||
- __auth_in_nano__: _number_
|
- __operations__: ARRAY of: _[UserOperation](#UserOperation)_
|
||||||
- __validate_in_nano__: _number_
|
|
||||||
- __handle_in_nano__: _number_
|
|
||||||
- __rpc_name__: _string_
|
|
||||||
- __batch__: _boolean_
|
|
||||||
- __nostr__: _boolean_
|
|
||||||
- __batch_size__: _number_
|
|
||||||
|
|
||||||
### UsersInfo
|
|
||||||
- __total__: _number_
|
|
||||||
- __no_balance__: _number_
|
|
||||||
- __negative_balance__: _number_
|
|
||||||
- __always_been_inactive__: _number_
|
|
||||||
- __balance_avg__: _number_
|
|
||||||
- __balance_median__: _number_
|
|
||||||
|
|
||||||
### PayInvoiceResponse
|
|
||||||
- __preimage__: _string_
|
|
||||||
- __amount_paid__: _number_
|
|
||||||
- __operation_id__: _string_
|
|
||||||
- __service_fee__: _number_
|
|
||||||
- __network_fee__: _number_
|
|
||||||
|
|
||||||
### AddAppUserRequest
|
|
||||||
- __identifier__: _string_
|
|
||||||
- __fail_if_exists__: _boolean_
|
|
||||||
- __balance__: _number_
|
|
||||||
|
|
||||||
### GetAppUserLNURLInfoRequest
|
|
||||||
- __user_identifier__: _string_
|
|
||||||
- __base_url_override__: _string_
|
|
||||||
|
|
||||||
### UserInfo
|
|
||||||
- __userId__: _string_
|
|
||||||
- __balance__: _number_
|
|
||||||
- __max_withdrawable__: _number_
|
|
||||||
- __user_identifier__: _string_
|
|
||||||
|
|
||||||
### AppUser
|
|
||||||
- __identifier__: _string_
|
|
||||||
- __info__: _[UserInfo](#UserInfo)_
|
|
||||||
- __max_withdrawable__: _number_
|
|
||||||
|
|
||||||
### NewAddressRequest
|
|
||||||
- __addressType__: _[AddressType](#AddressType)_
|
|
||||||
|
|
||||||
### ChainBalanceEvent
|
### ChainBalanceEvent
|
||||||
- __block_height__: _number_
|
- __block_height__: _number_
|
||||||
|
|
@ -662,21 +650,6 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- __unconfirmed_balance__: _number_
|
- __unconfirmed_balance__: _number_
|
||||||
- __total_balance__: _number_
|
- __total_balance__: _number_
|
||||||
|
|
||||||
### SetMockAppBalanceRequest
|
|
||||||
- __amount__: _number_
|
|
||||||
|
|
||||||
### GetUserOperationsResponse
|
|
||||||
- __latestOutgoingInvoiceOperations__: _[UserOperations](#UserOperations)_
|
|
||||||
- __latestIncomingInvoiceOperations__: _[UserOperations](#UserOperations)_
|
|
||||||
- __latestOutgoingTxOperations__: _[UserOperations](#UserOperations)_
|
|
||||||
- __latestIncomingTxOperations__: _[UserOperations](#UserOperations)_
|
|
||||||
- __latestOutgoingUserToUserPayemnts__: _[UserOperations](#UserOperations)_
|
|
||||||
- __latestIncomingUserToUserPayemnts__: _[UserOperations](#UserOperations)_
|
|
||||||
|
|
||||||
### AddProductRequest
|
|
||||||
- __name__: _string_
|
|
||||||
- __price_sats__: _number_
|
|
||||||
|
|
||||||
### LndNodeMetrics
|
### LndNodeMetrics
|
||||||
- __channels_balance_events__: ARRAY of: _[ChannelBalanceEvent](#ChannelBalanceEvent)_
|
- __channels_balance_events__: ARRAY of: _[ChannelBalanceEvent](#ChannelBalanceEvent)_
|
||||||
- __chain_balance_events__: ARRAY of: _[ChainBalanceEvent](#ChainBalanceEvent)_
|
- __chain_balance_events__: ARRAY of: _[ChainBalanceEvent](#ChainBalanceEvent)_
|
||||||
|
|
@ -688,90 +661,109 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- __closed_channels__: ARRAY of: _[ClosedChannel](#ClosedChannel)_
|
- __closed_channels__: ARRAY of: _[ClosedChannel](#ClosedChannel)_
|
||||||
- __channel_routing__: ARRAY of: _[ChannelRouting](#ChannelRouting)_
|
- __channel_routing__: ARRAY of: _[ChannelRouting](#ChannelRouting)_
|
||||||
|
|
||||||
### SendAppUserToAppPaymentRequest
|
### SetMockInvoiceAsPaidRequest
|
||||||
- __from_user_identifier__: _string_
|
- __invoice__: _string_
|
||||||
- __amount__: _number_
|
- __amount__: _number_
|
||||||
|
|
||||||
### DecodeInvoiceResponse
|
|
||||||
- __amount__: _number_
|
|
||||||
|
|
||||||
### OpenChannelRequest
|
|
||||||
- __destination__: _string_
|
|
||||||
- __fundingAmount__: _number_
|
|
||||||
- __pushAmount__: _number_
|
|
||||||
- __closeAddress__: _string_
|
|
||||||
|
|
||||||
### LndGetInfoResponse
|
|
||||||
- __alias__: _string_
|
|
||||||
|
|
||||||
### AddAppRequest
|
|
||||||
- __name__: _string_
|
|
||||||
- __allow_user_creation__: _boolean_
|
|
||||||
|
|
||||||
### AddAppUserInvoiceRequest
|
### AddAppUserInvoiceRequest
|
||||||
- __receiver_identifier__: _string_
|
- __receiver_identifier__: _string_
|
||||||
- __payer_identifier__: _string_
|
- __payer_identifier__: _string_
|
||||||
- __http_callback_url__: _string_
|
- __http_callback_url__: _string_
|
||||||
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
|
- __invoice_req__: _[NewInvoiceRequest](#NewInvoiceRequest)_
|
||||||
|
|
||||||
### LndMetrics
|
### OpenChannelRequest
|
||||||
- __nodes__: ARRAY of: _[LndNodeMetrics](#LndNodeMetrics)_
|
- __destination__: _string_
|
||||||
|
- __fundingAmount__: _number_
|
||||||
### LndGetInfoRequest
|
- __pushAmount__: _number_
|
||||||
- __nodeId__: _number_
|
- __closeAddress__: _string_
|
||||||
|
|
||||||
### DecodeInvoiceRequest
|
|
||||||
- __invoice__: _string_
|
|
||||||
|
|
||||||
### UserOperations
|
|
||||||
- __fromIndex__: _number_
|
|
||||||
- __toIndex__: _number_
|
|
||||||
- __operations__: ARRAY of: _[UserOperation](#UserOperation)_
|
|
||||||
|
|
||||||
### Product
|
|
||||||
- __id__: _string_
|
|
||||||
- __name__: _string_
|
|
||||||
- __price_sats__: _number_
|
|
||||||
|
|
||||||
### RelaysMigration
|
|
||||||
- __relays__: ARRAY of: _string_
|
|
||||||
|
|
||||||
### LiveUserOperation
|
|
||||||
- __operation__: _[UserOperation](#UserOperation)_
|
|
||||||
|
|
||||||
### RequestNPubLinkingTokenResponse
|
|
||||||
- __token__: _string_
|
|
||||||
|
|
||||||
### UsageMetrics
|
### UsageMetrics
|
||||||
- __metrics__: ARRAY of: _[UsageMetric](#UsageMetric)_
|
- __metrics__: ARRAY of: _[UsageMetric](#UsageMetric)_
|
||||||
|
|
||||||
### AppsMetrics
|
### OpenChannel
|
||||||
- __apps__: ARRAY of: _[AppMetrics](#AppMetrics)_
|
|
||||||
|
|
||||||
### ClosedChannel
|
|
||||||
- __channel_id__: _string_
|
- __channel_id__: _string_
|
||||||
- __capacity__: _number_
|
- __capacity__: _number_
|
||||||
- __closed_height__: _number_
|
- __active__: _boolean_
|
||||||
|
- __lifetime__: _number_
|
||||||
|
- __local_balance__: _number_
|
||||||
|
- __remote_balance__: _number_
|
||||||
|
|
||||||
### UserOperation
|
### NewAddressRequest
|
||||||
- __paidAtUnix__: _number_
|
- __addressType__: _[AddressType](#AddressType)_
|
||||||
- __type__: _[UserOperationType](#UserOperationType)_
|
|
||||||
- __inbound__: _boolean_
|
### LnurlPayInfoResponse
|
||||||
|
- __tag__: _string_
|
||||||
|
- __callback__: _string_
|
||||||
|
- __maxSendable__: _number_
|
||||||
|
- __minSendable__: _number_
|
||||||
|
- __metadata__: _string_
|
||||||
|
- __allowsNostr__: _boolean_
|
||||||
|
- __nostrPubkey__: _string_
|
||||||
|
|
||||||
|
### GetProductBuyLinkResponse
|
||||||
|
- __link__: _string_
|
||||||
|
|
||||||
|
### UsersInfo
|
||||||
|
- __total__: _number_
|
||||||
|
- __no_balance__: _number_
|
||||||
|
- __negative_balance__: _number_
|
||||||
|
- __always_been_inactive__: _number_
|
||||||
|
- __balance_avg__: _number_
|
||||||
|
- __balance_median__: _number_
|
||||||
|
|
||||||
|
### AddAppRequest
|
||||||
|
- __name__: _string_
|
||||||
|
- __allow_user_creation__: _boolean_
|
||||||
|
|
||||||
|
### DecodeInvoiceResponse
|
||||||
- __amount__: _number_
|
- __amount__: _number_
|
||||||
- __identifier__: _string_
|
|
||||||
- __operationId__: _string_
|
### LndMetrics
|
||||||
|
- __nodes__: ARRAY of: _[LndNodeMetrics](#LndNodeMetrics)_
|
||||||
|
|
||||||
|
### AddProductRequest
|
||||||
|
- __name__: _string_
|
||||||
|
- __price_sats__: _number_
|
||||||
|
|
||||||
|
### Empty
|
||||||
|
|
||||||
|
### ChannelRouting
|
||||||
|
- __channel_id__: _string_
|
||||||
|
- __send_errors__: _number_
|
||||||
|
- __receive_errors__: _number_
|
||||||
|
- __forward_errors_as_input__: _number_
|
||||||
|
- __forward_errors_as_output__: _number_
|
||||||
|
- __missed_forward_fee_as_input__: _number_
|
||||||
|
- __missed_forward_fee_as_output__: _number_
|
||||||
|
- __forward_fee_as_input__: _number_
|
||||||
|
- __forward_fee_as_output__: _number_
|
||||||
|
- __events_number__: _number_
|
||||||
|
|
||||||
|
### PayInvoiceResponse
|
||||||
|
- __preimage__: _string_
|
||||||
|
- __amount_paid__: _number_
|
||||||
|
- __operation_id__: _string_
|
||||||
- __service_fee__: _number_
|
- __service_fee__: _number_
|
||||||
- __network_fee__: _number_
|
- __network_fee__: _number_
|
||||||
- __confirmed__: _boolean_
|
|
||||||
- __tx_hash__: _string_
|
|
||||||
- __internal__: _boolean_
|
|
||||||
|
|
||||||
### SetMockInvoiceAsPaidRequest
|
### UserInfo
|
||||||
- __invoice__: _string_
|
- __userId__: _string_
|
||||||
- __amount__: _number_
|
- __balance__: _number_
|
||||||
|
- __max_withdrawable__: _number_
|
||||||
|
- __user_identifier__: _string_
|
||||||
|
|
||||||
### BanUserRequest
|
### MigrationUpdate
|
||||||
- __user_id__: _string_
|
- __closure__: _[ClosureMigration](#ClosureMigration)_ *this field is optional
|
||||||
|
- __relays__: _[RelaysMigration](#RelaysMigration)_ *this field is optional
|
||||||
|
|
||||||
|
### LinkNPubThroughTokenRequest
|
||||||
|
- __token__: _string_
|
||||||
|
- __nostr_pub__: _string_
|
||||||
|
|
||||||
|
### PayAddressRequest
|
||||||
|
- __address__: _string_
|
||||||
|
- __amoutSats__: _number_
|
||||||
|
- __satsPerVByte__: _number_
|
||||||
|
|
||||||
### PayAddressResponse
|
### PayAddressResponse
|
||||||
- __txId__: _string_
|
- __txId__: _string_
|
||||||
|
|
@ -779,24 +771,6 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- __service_fee__: _number_
|
- __service_fee__: _number_
|
||||||
- __network_fee__: _number_
|
- __network_fee__: _number_
|
||||||
|
|
||||||
### GetUserOperationsRequest
|
|
||||||
- __latestIncomingInvoice__: _number_
|
|
||||||
- __latestOutgoingInvoice__: _number_
|
|
||||||
- __latestIncomingTx__: _number_
|
|
||||||
- __latestOutgoingTx__: _number_
|
|
||||||
- __latestIncomingUserToUserPayment__: _number_
|
|
||||||
- __latestOutgoingUserToUserPayment__: _number_
|
|
||||||
- __max_size__: _number_
|
|
||||||
|
|
||||||
### EncryptionExchangeRequest
|
|
||||||
- __publicKey__: _string_
|
|
||||||
- __deviceId__: _string_
|
|
||||||
|
|
||||||
### AppsMetricsRequest
|
|
||||||
- __from_unix__: _number_ *this field is optional
|
|
||||||
- __to_unix__: _number_ *this field is optional
|
|
||||||
- __include_operations__: _boolean_ *this field is optional
|
|
||||||
|
|
||||||
### AppMetrics
|
### AppMetrics
|
||||||
- __app__: _[Application](#Application)_
|
- __app__: _[Application](#Application)_
|
||||||
- __users__: _[UsersInfo](#UsersInfo)_
|
- __users__: _[UsersInfo](#UsersInfo)_
|
||||||
|
|
@ -808,26 +782,68 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- __total_fees__: _number_
|
- __total_fees__: _number_
|
||||||
- __operations__: ARRAY of: _[UserOperation](#UserOperation)_
|
- __operations__: ARRAY of: _[UserOperation](#UserOperation)_
|
||||||
|
|
||||||
### ChannelBalanceEvent
|
### BanUserResponse
|
||||||
- __block_height__: _number_
|
- __balance_sats__: _number_
|
||||||
- __channel_id__: _string_
|
- __banned_app_users__: ARRAY of: _[BannedAppUser](#BannedAppUser)_
|
||||||
- __local_balance_sats__: _number_
|
|
||||||
- __remote_balance_sats__: _number_
|
|
||||||
|
|
||||||
### RequestNPubLinkingTokenRequest
|
### AuthApp
|
||||||
- __user_identifier__: _string_
|
- __app__: _[Application](#Application)_
|
||||||
|
- __auth_token__: _string_
|
||||||
|
|
||||||
### LndMetricsRequest
|
### LndMetricsRequest
|
||||||
- __from_unix__: _number_ *this field is optional
|
- __from_unix__: _number_ *this field is optional
|
||||||
- __to_unix__: _number_ *this field is optional
|
- __to_unix__: _number_ *this field is optional
|
||||||
|
|
||||||
|
### BannedAppUser
|
||||||
|
- __app_name__: _string_
|
||||||
|
- __app_id__: _string_
|
||||||
|
- __user_identifier__: _string_
|
||||||
|
- __nostr_pub__: _string_
|
||||||
|
|
||||||
|
### GetAppUserRequest
|
||||||
|
- __user_identifier__: _string_
|
||||||
|
|
||||||
|
### SetMockAppBalanceRequest
|
||||||
|
- __amount__: _number_
|
||||||
|
|
||||||
|
### DecodeInvoiceRequest
|
||||||
|
- __invoice__: _string_
|
||||||
|
|
||||||
|
### RequestNPubLinkingTokenResponse
|
||||||
|
- __token__: _string_
|
||||||
|
|
||||||
|
### LndGetInfoRequest
|
||||||
|
- __nodeId__: _number_
|
||||||
|
|
||||||
|
### AppUser
|
||||||
|
- __identifier__: _string_
|
||||||
|
- __info__: _[UserInfo](#UserInfo)_
|
||||||
|
- __max_withdrawable__: _number_
|
||||||
|
|
||||||
|
### SetMockAppUserBalanceRequest
|
||||||
|
- __user_identifier__: _string_
|
||||||
|
- __amount__: _number_
|
||||||
|
|
||||||
### PayInvoiceRequest
|
### PayInvoiceRequest
|
||||||
- __invoice__: _string_
|
- __invoice__: _string_
|
||||||
- __amount__: _number_
|
- __amount__: _number_
|
||||||
|
|
||||||
### LnurlLinkResponse
|
### AddAppUserRequest
|
||||||
- __lnurl__: _string_
|
- __identifier__: _string_
|
||||||
- __k1__: _string_
|
- __fail_if_exists__: _boolean_
|
||||||
|
- __balance__: _number_
|
||||||
|
|
||||||
|
### NewInvoiceResponse
|
||||||
|
- __invoice__: _string_
|
||||||
|
|
||||||
|
### AppsMetrics
|
||||||
|
- __apps__: ARRAY of: _[AppMetrics](#AppMetrics)_
|
||||||
|
|
||||||
|
### LndGetInfoResponse
|
||||||
|
- __alias__: _string_
|
||||||
|
|
||||||
|
### NewAddressResponse
|
||||||
|
- __address__: _string_
|
||||||
## Enums
|
## Enums
|
||||||
### The enumerators used in the messages
|
### The enumerators used in the messages
|
||||||
|
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -587,6 +587,7 @@ export default (params: ClientParams) => ({
|
||||||
},
|
},
|
||||||
GetLiveUserOperations: async (cb: (v:ResultError | ({ status: 'OK' }& Types.LiveUserOperation)) => void): Promise<void> => { throw new Error('http streams are not supported')},
|
GetLiveUserOperations: async (cb: (v:ResultError | ({ status: 'OK' }& Types.LiveUserOperation)) => void): Promise<void> => { throw new Error('http streams are not supported')},
|
||||||
GetMigrationUpdate: async (cb: (v:ResultError | ({ status: 'OK' }& Types.MigrationUpdate)) => void): Promise<void> => { throw new Error('http streams are not supported')},
|
GetMigrationUpdate: async (cb: (v:ResultError | ({ status: 'OK' }& Types.MigrationUpdate)) => void): Promise<void> => { throw new Error('http streams are not supported')},
|
||||||
|
GetHttpCreds: async (cb: (v:ResultError | ({ status: 'OK' }& Types.HttpCreds)) => void): Promise<void> => { throw new Error('http streams are not supported')},
|
||||||
BatchUser: async (requests:Types.UserMethodInputs[]): Promise<ResultError | ({ status: 'OK', responses:( Types.UserMethodOutputs)[] })> => {
|
BatchUser: async (requests:Types.UserMethodInputs[]): Promise<ResultError | ({ status: 'OK', responses:( Types.UserMethodOutputs)[] })> => {
|
||||||
const auth = await params.retrieveUserAuth()
|
const auth = await params.retrieveUserAuth()
|
||||||
if (auth === null) throw new Error('retrieveUserAuth() returned null')
|
if (auth === null) throw new Error('retrieveUserAuth() returned null')
|
||||||
|
|
|
||||||
|
|
@ -253,6 +253,21 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ
|
||||||
return cb({ status: 'ERROR', reason: 'invalid response' })
|
return cb({ status: 'ERROR', reason: 'invalid response' })
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
GetHttpCreds: async (cb: (res:ResultError | ({ status: 'OK' }& Types.HttpCreds)) => void): Promise<void> => {
|
||||||
|
const auth = await params.retrieveNostrUserAuth()
|
||||||
|
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
|
||||||
|
const nostrRequest: NostrRequest = {}
|
||||||
|
subscribe(params.pubDestination, {rpcName:'GetHttpCreds',authIdentifier:auth, ...nostrRequest }, (data) => {
|
||||||
|
if (data.status === 'ERROR' && typeof data.reason === 'string') return cb(data)
|
||||||
|
if (data.status === 'OK') {
|
||||||
|
const result = data
|
||||||
|
if(!params.checkResult) return cb({ status: 'OK', ...result })
|
||||||
|
const error = Types.HttpCredsValidate(result)
|
||||||
|
if (error === null) { return cb({ status: 'OK', ...result }) } else return cb({ status: 'ERROR', reason: error.message })
|
||||||
|
}
|
||||||
|
return cb({ status: 'ERROR', reason: 'invalid response' })
|
||||||
|
})
|
||||||
|
},
|
||||||
BatchUser: async (requests:Types.UserMethodInputs[]): Promise<ResultError | ({ status: 'OK', responses:(Types.UserMethodOutputs)[] })> => {
|
BatchUser: async (requests:Types.UserMethodInputs[]): Promise<ResultError | ({ status: 'OK', responses:(Types.UserMethodOutputs)[] })> => {
|
||||||
const auth = await params.retrieveNostrUserAuth()
|
const auth = await params.retrieveNostrUserAuth()
|
||||||
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
|
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,7 @@ export type NostrOptions = {
|
||||||
logger?: Logger
|
logger?: Logger
|
||||||
throwErrors?: true
|
throwErrors?: true
|
||||||
metricsCallback: (metrics: Types.RequestMetric[]) => void
|
metricsCallback: (metrics: Types.RequestMetric[]) => void
|
||||||
NostrUserAuthGuard: (appId?:string, identifier?: string) => Promise<Types.UserContext>
|
NostrUserAuthGuard: (appId?: string, identifier?: string) => Promise<Types.UserContext>
|
||||||
}
|
}
|
||||||
const logErrorAndReturnResponse = (error: Error, response: string, res: NostrResponse, logger: Logger, metric: Types.RequestMetric, metricsCallback: (metrics: Types.RequestMetric[]) => void) => {
|
const logErrorAndReturnResponse = (error: Error, response: string, res: NostrResponse, logger: Logger, metric: Types.RequestMetric, metricsCallback: (metrics: Types.RequestMetric[]) => void) => {
|
||||||
logger.error(error.message || error); metricsCallback([{ ...metric, error: response }]); res({ status: 'ERROR', reason: response })
|
logger.error(error.message || error); metricsCallback([{ ...metric, error: response }]); res({ status: 'ERROR', reason: response })
|
||||||
|
|
@ -39,11 +39,11 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.LinkNPubThroughTokenRequestValidate(request)
|
const error = Types.LinkNPubThroughTokenRequestValidate(request)
|
||||||
stats.validate = process.hrtime.bigint()
|
stats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
||||||
await methods.LinkNPubThroughToken({rpcName:'LinkNPubThroughToken', ctx:authContext , req: request})
|
await methods.LinkNPubThroughToken({ rpcName: 'LinkNPubThroughToken', ctx: authContext, req: request })
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
res({status: 'OK'})
|
res({ status: 'OK' })
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
case 'UserHealth':
|
case 'UserHealth':
|
||||||
try {
|
try {
|
||||||
|
|
@ -52,11 +52,11 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
stats.guard = process.hrtime.bigint()
|
stats.guard = process.hrtime.bigint()
|
||||||
authCtx = authContext
|
authCtx = authContext
|
||||||
stats.validate = stats.guard
|
stats.validate = stats.guard
|
||||||
await methods.UserHealth({rpcName:'UserHealth', ctx:authContext })
|
await methods.UserHealth({ rpcName: 'UserHealth', ctx: authContext })
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
res({status: 'OK'})
|
res({ status: 'OK' })
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
case 'GetUserInfo':
|
case 'GetUserInfo':
|
||||||
try {
|
try {
|
||||||
|
|
@ -65,11 +65,11 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
stats.guard = process.hrtime.bigint()
|
stats.guard = process.hrtime.bigint()
|
||||||
authCtx = authContext
|
authCtx = authContext
|
||||||
stats.validate = stats.guard
|
stats.validate = stats.guard
|
||||||
const response = await methods.GetUserInfo({rpcName:'GetUserInfo', ctx:authContext })
|
const response = await methods.GetUserInfo({ rpcName: 'GetUserInfo', ctx: authContext })
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
res({status: 'OK', ...response})
|
res({ status: 'OK', ...response })
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
case 'AddProduct':
|
case 'AddProduct':
|
||||||
try {
|
try {
|
||||||
|
|
@ -81,11 +81,11 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.AddProductRequestValidate(request)
|
const error = Types.AddProductRequestValidate(request)
|
||||||
stats.validate = process.hrtime.bigint()
|
stats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
||||||
const response = await methods.AddProduct({rpcName:'AddProduct', ctx:authContext , req: request})
|
const response = await methods.AddProduct({ rpcName: 'AddProduct', ctx: authContext, req: request })
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
res({status: 'OK', ...response})
|
res({ status: 'OK', ...response })
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
case 'NewProductInvoice':
|
case 'NewProductInvoice':
|
||||||
try {
|
try {
|
||||||
|
|
@ -94,11 +94,11 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
stats.guard = process.hrtime.bigint()
|
stats.guard = process.hrtime.bigint()
|
||||||
authCtx = authContext
|
authCtx = authContext
|
||||||
stats.validate = stats.guard
|
stats.validate = stats.guard
|
||||||
const response = await methods.NewProductInvoice({rpcName:'NewProductInvoice', ctx:authContext ,query: req.query||{}})
|
const response = await methods.NewProductInvoice({ rpcName: 'NewProductInvoice', ctx: authContext, query: req.query || {} })
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
res({status: 'OK', ...response})
|
res({ status: 'OK', ...response })
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
case 'GetUserOperations':
|
case 'GetUserOperations':
|
||||||
try {
|
try {
|
||||||
|
|
@ -110,11 +110,11 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.GetUserOperationsRequestValidate(request)
|
const error = Types.GetUserOperationsRequestValidate(request)
|
||||||
stats.validate = process.hrtime.bigint()
|
stats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
||||||
const response = await methods.GetUserOperations({rpcName:'GetUserOperations', ctx:authContext , req: request})
|
const response = await methods.GetUserOperations({ rpcName: 'GetUserOperations', ctx: authContext, req: request })
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
res({status: 'OK', ...response})
|
res({ status: 'OK', ...response })
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
case 'NewAddress':
|
case 'NewAddress':
|
||||||
try {
|
try {
|
||||||
|
|
@ -126,11 +126,11 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.NewAddressRequestValidate(request)
|
const error = Types.NewAddressRequestValidate(request)
|
||||||
stats.validate = process.hrtime.bigint()
|
stats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
||||||
const response = await methods.NewAddress({rpcName:'NewAddress', ctx:authContext , req: request})
|
const response = await methods.NewAddress({ rpcName: 'NewAddress', ctx: authContext, req: request })
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
res({status: 'OK', ...response})
|
res({ status: 'OK', ...response })
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
case 'PayAddress':
|
case 'PayAddress':
|
||||||
try {
|
try {
|
||||||
|
|
@ -142,11 +142,11 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.PayAddressRequestValidate(request)
|
const error = Types.PayAddressRequestValidate(request)
|
||||||
stats.validate = process.hrtime.bigint()
|
stats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
||||||
const response = await methods.PayAddress({rpcName:'PayAddress', ctx:authContext , req: request})
|
const response = await methods.PayAddress({ rpcName: 'PayAddress', ctx: authContext, req: request })
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
res({status: 'OK', ...response})
|
res({ status: 'OK', ...response })
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
case 'NewInvoice':
|
case 'NewInvoice':
|
||||||
try {
|
try {
|
||||||
|
|
@ -158,11 +158,11 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.NewInvoiceRequestValidate(request)
|
const error = Types.NewInvoiceRequestValidate(request)
|
||||||
stats.validate = process.hrtime.bigint()
|
stats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
||||||
const response = await methods.NewInvoice({rpcName:'NewInvoice', ctx:authContext , req: request})
|
const response = await methods.NewInvoice({ rpcName: 'NewInvoice', ctx: authContext, req: request })
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
res({status: 'OK', ...response})
|
res({ status: 'OK', ...response })
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
case 'DecodeInvoice':
|
case 'DecodeInvoice':
|
||||||
try {
|
try {
|
||||||
|
|
@ -174,11 +174,11 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.DecodeInvoiceRequestValidate(request)
|
const error = Types.DecodeInvoiceRequestValidate(request)
|
||||||
stats.validate = process.hrtime.bigint()
|
stats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
||||||
const response = await methods.DecodeInvoice({rpcName:'DecodeInvoice', ctx:authContext , req: request})
|
const response = await methods.DecodeInvoice({ rpcName: 'DecodeInvoice', ctx: authContext, req: request })
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
res({status: 'OK', ...response})
|
res({ status: 'OK', ...response })
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
case 'PayInvoice':
|
case 'PayInvoice':
|
||||||
try {
|
try {
|
||||||
|
|
@ -190,11 +190,11 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.PayInvoiceRequestValidate(request)
|
const error = Types.PayInvoiceRequestValidate(request)
|
||||||
stats.validate = process.hrtime.bigint()
|
stats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
||||||
const response = await methods.PayInvoice({rpcName:'PayInvoice', ctx:authContext , req: request})
|
const response = await methods.PayInvoice({ rpcName: 'PayInvoice', ctx: authContext, req: request })
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
res({status: 'OK', ...response})
|
res({ status: 'OK', ...response })
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
case 'OpenChannel':
|
case 'OpenChannel':
|
||||||
try {
|
try {
|
||||||
|
|
@ -206,11 +206,11 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.OpenChannelRequestValidate(request)
|
const error = Types.OpenChannelRequestValidate(request)
|
||||||
stats.validate = process.hrtime.bigint()
|
stats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
||||||
const response = await methods.OpenChannel({rpcName:'OpenChannel', ctx:authContext , req: request})
|
const response = await methods.OpenChannel({ rpcName: 'OpenChannel', ctx: authContext, req: request })
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
res({status: 'OK', ...response})
|
res({ status: 'OK', ...response })
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
case 'GetLnurlWithdrawLink':
|
case 'GetLnurlWithdrawLink':
|
||||||
try {
|
try {
|
||||||
|
|
@ -219,11 +219,11 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
stats.guard = process.hrtime.bigint()
|
stats.guard = process.hrtime.bigint()
|
||||||
authCtx = authContext
|
authCtx = authContext
|
||||||
stats.validate = stats.guard
|
stats.validate = stats.guard
|
||||||
const response = await methods.GetLnurlWithdrawLink({rpcName:'GetLnurlWithdrawLink', ctx:authContext })
|
const response = await methods.GetLnurlWithdrawLink({ rpcName: 'GetLnurlWithdrawLink', ctx: authContext })
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
res({status: 'OK', ...response})
|
res({ status: 'OK', ...response })
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
case 'GetLnurlPayLink':
|
case 'GetLnurlPayLink':
|
||||||
try {
|
try {
|
||||||
|
|
@ -232,11 +232,11 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
stats.guard = process.hrtime.bigint()
|
stats.guard = process.hrtime.bigint()
|
||||||
authCtx = authContext
|
authCtx = authContext
|
||||||
stats.validate = stats.guard
|
stats.validate = stats.guard
|
||||||
const response = await methods.GetLnurlPayLink({rpcName:'GetLnurlPayLink', ctx:authContext })
|
const response = await methods.GetLnurlPayLink({ rpcName: 'GetLnurlPayLink', ctx: authContext })
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
res({status: 'OK', ...response})
|
res({ status: 'OK', ...response })
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
case 'GetLNURLChannelLink':
|
case 'GetLNURLChannelLink':
|
||||||
try {
|
try {
|
||||||
|
|
@ -245,11 +245,11 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
stats.guard = process.hrtime.bigint()
|
stats.guard = process.hrtime.bigint()
|
||||||
authCtx = authContext
|
authCtx = authContext
|
||||||
stats.validate = stats.guard
|
stats.validate = stats.guard
|
||||||
const response = await methods.GetLNURLChannelLink({rpcName:'GetLNURLChannelLink', ctx:authContext })
|
const response = await methods.GetLNURLChannelLink({ rpcName: 'GetLNURLChannelLink', ctx: authContext })
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
res({status: 'OK', ...response})
|
res({ status: 'OK', ...response })
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
case 'GetLiveUserOperations':
|
case 'GetLiveUserOperations':
|
||||||
try {
|
try {
|
||||||
|
|
@ -258,11 +258,13 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
stats.guard = process.hrtime.bigint()
|
stats.guard = process.hrtime.bigint()
|
||||||
authCtx = authContext
|
authCtx = authContext
|
||||||
stats.validate = stats.guard
|
stats.validate = stats.guard
|
||||||
methods.GetLiveUserOperations({rpcName:'GetLiveUserOperations', ctx:authContext ,cb: (response, err) => {
|
methods.GetLiveUserOperations({
|
||||||
|
rpcName: 'GetLiveUserOperations', ctx: authContext, cb: (response, err) => {
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
if (err) { logErrorAndReturnResponse(err, err.message, res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback)} else { res({status: 'OK', ...response});opts.metricsCallback([{ ...info, ...stats, ...authContext }])}
|
if (err) { logErrorAndReturnResponse(err, err.message, res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback) } else { res({ status: 'OK', ...response }); opts.metricsCallback([{ ...info, ...stats, ...authContext }]) }
|
||||||
}})
|
}
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
})
|
||||||
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
case 'GetMigrationUpdate':
|
case 'GetMigrationUpdate':
|
||||||
try {
|
try {
|
||||||
|
|
@ -271,17 +273,34 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
stats.guard = process.hrtime.bigint()
|
stats.guard = process.hrtime.bigint()
|
||||||
authCtx = authContext
|
authCtx = authContext
|
||||||
stats.validate = stats.guard
|
stats.validate = stats.guard
|
||||||
methods.GetMigrationUpdate({rpcName:'GetMigrationUpdate', ctx:authContext ,cb: (response, err) => {
|
methods.GetMigrationUpdate({
|
||||||
|
rpcName: 'GetMigrationUpdate', ctx: authContext, cb: (response, err) => {
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
if (err) { logErrorAndReturnResponse(err, err.message, res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback)} else { res({status: 'OK', ...response});opts.metricsCallback([{ ...info, ...stats, ...authContext }])}
|
if (err) { logErrorAndReturnResponse(err, err.message, res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback) } else { res({ status: 'OK', ...response }); opts.metricsCallback([{ ...info, ...stats, ...authContext }]) }
|
||||||
}})
|
}
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
})
|
||||||
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
|
break
|
||||||
|
case 'GetHttpCreds':
|
||||||
|
try {
|
||||||
|
if (!methods.GetHttpCreds) throw new Error('method: GetHttpCreds is not implemented')
|
||||||
|
const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
|
||||||
|
stats.guard = process.hrtime.bigint()
|
||||||
|
authCtx = authContext
|
||||||
|
stats.validate = stats.guard
|
||||||
|
methods.GetHttpCreds({
|
||||||
|
rpcName: 'GetHttpCreds', ctx: authContext, cb: (response, err) => {
|
||||||
|
stats.handle = process.hrtime.bigint()
|
||||||
|
if (err) { logErrorAndReturnResponse(err, err.message, res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback) } else { res({ status: 'OK', ...response }); opts.metricsCallback([{ ...info, ...stats, ...authContext }]) }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
case 'BatchUser':
|
case 'BatchUser':
|
||||||
try {
|
try {
|
||||||
info.batch = true
|
info.batch = true
|
||||||
const requests = req.body.requests as Types.UserMethodInputs[]
|
const requests = req.body.requests as Types.UserMethodInputs[]
|
||||||
if (!Array.isArray(requests))throw new Error('invalid body, is not an array')
|
if (!Array.isArray(requests)) throw new Error('invalid body, is not an array')
|
||||||
info.batchSize = requests.length
|
info.batchSize = requests.length
|
||||||
if (requests.length > 10) throw new Error('too many requests in the batch')
|
if (requests.length > 10) throw new Error('too many requests in the batch')
|
||||||
const ctx = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
|
const ctx = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier)
|
||||||
|
|
@ -295,7 +314,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const opInfo: Types.RequestInfo = { rpcName: operation.rpcName, batch: true, nostr: true, batchSize: 0 }
|
const opInfo: Types.RequestInfo = { rpcName: operation.rpcName, batch: true, nostr: true, batchSize: 0 }
|
||||||
const opStats: Types.RequestStats = { startMs, start: startTime, parse: stats.parse, guard: stats.guard, validate: 0n, handle: 0n }
|
const opStats: Types.RequestStats = { startMs, start: startTime, parse: stats.parse, guard: stats.guard, validate: 0n, handle: 0n }
|
||||||
try {
|
try {
|
||||||
switch(operation.rpcName) {
|
switch (operation.rpcName) {
|
||||||
case 'LinkNPubThroughToken':
|
case 'LinkNPubThroughToken':
|
||||||
if (!methods.LinkNPubThroughToken) {
|
if (!methods.LinkNPubThroughToken) {
|
||||||
throw new Error('method not defined: LinkNPubThroughToken')
|
throw new Error('method not defined: LinkNPubThroughToken')
|
||||||
|
|
@ -303,7 +322,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.LinkNPubThroughTokenRequestValidate(operation.req)
|
const error = Types.LinkNPubThroughTokenRequestValidate(operation.req)
|
||||||
opStats.validate = process.hrtime.bigint()
|
opStats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) throw error
|
if (error !== null) throw error
|
||||||
await methods.LinkNPubThroughToken({...operation, ctx}); responses.push({ status: 'OK' })
|
await methods.LinkNPubThroughToken({ ...operation, ctx }); responses.push({ status: 'OK' })
|
||||||
opStats.handle = process.hrtime.bigint()
|
opStats.handle = process.hrtime.bigint()
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
|
|
@ -313,7 +332,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
throw new Error('method not defined: UserHealth')
|
throw new Error('method not defined: UserHealth')
|
||||||
} else {
|
} else {
|
||||||
opStats.validate = opStats.guard
|
opStats.validate = opStats.guard
|
||||||
await methods.UserHealth({...operation, ctx}); responses.push({ status: 'OK' })
|
await methods.UserHealth({ ...operation, ctx }); responses.push({ status: 'OK' })
|
||||||
opStats.handle = process.hrtime.bigint()
|
opStats.handle = process.hrtime.bigint()
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
|
|
@ -323,7 +342,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
throw new Error('method not defined: GetUserInfo')
|
throw new Error('method not defined: GetUserInfo')
|
||||||
} else {
|
} else {
|
||||||
opStats.validate = opStats.guard
|
opStats.validate = opStats.guard
|
||||||
const res = await methods.GetUserInfo({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
const res = await methods.GetUserInfo({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
|
||||||
opStats.handle = process.hrtime.bigint()
|
opStats.handle = process.hrtime.bigint()
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
|
|
@ -335,7 +354,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.AddProductRequestValidate(operation.req)
|
const error = Types.AddProductRequestValidate(operation.req)
|
||||||
opStats.validate = process.hrtime.bigint()
|
opStats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) throw error
|
if (error !== null) throw error
|
||||||
const res = await methods.AddProduct({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
const res = await methods.AddProduct({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
|
||||||
opStats.handle = process.hrtime.bigint()
|
opStats.handle = process.hrtime.bigint()
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
|
|
@ -345,7 +364,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
throw new Error('method not defined: NewProductInvoice')
|
throw new Error('method not defined: NewProductInvoice')
|
||||||
} else {
|
} else {
|
||||||
opStats.validate = opStats.guard
|
opStats.validate = opStats.guard
|
||||||
const res = await methods.NewProductInvoice({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
const res = await methods.NewProductInvoice({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
|
||||||
opStats.handle = process.hrtime.bigint()
|
opStats.handle = process.hrtime.bigint()
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
|
|
@ -357,7 +376,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.GetUserOperationsRequestValidate(operation.req)
|
const error = Types.GetUserOperationsRequestValidate(operation.req)
|
||||||
opStats.validate = process.hrtime.bigint()
|
opStats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) throw error
|
if (error !== null) throw error
|
||||||
const res = await methods.GetUserOperations({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
const res = await methods.GetUserOperations({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
|
||||||
opStats.handle = process.hrtime.bigint()
|
opStats.handle = process.hrtime.bigint()
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
|
|
@ -369,7 +388,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.NewAddressRequestValidate(operation.req)
|
const error = Types.NewAddressRequestValidate(operation.req)
|
||||||
opStats.validate = process.hrtime.bigint()
|
opStats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) throw error
|
if (error !== null) throw error
|
||||||
const res = await methods.NewAddress({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
const res = await methods.NewAddress({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
|
||||||
opStats.handle = process.hrtime.bigint()
|
opStats.handle = process.hrtime.bigint()
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
|
|
@ -381,7 +400,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.PayAddressRequestValidate(operation.req)
|
const error = Types.PayAddressRequestValidate(operation.req)
|
||||||
opStats.validate = process.hrtime.bigint()
|
opStats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) throw error
|
if (error !== null) throw error
|
||||||
const res = await methods.PayAddress({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
const res = await methods.PayAddress({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
|
||||||
opStats.handle = process.hrtime.bigint()
|
opStats.handle = process.hrtime.bigint()
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
|
|
@ -393,7 +412,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.NewInvoiceRequestValidate(operation.req)
|
const error = Types.NewInvoiceRequestValidate(operation.req)
|
||||||
opStats.validate = process.hrtime.bigint()
|
opStats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) throw error
|
if (error !== null) throw error
|
||||||
const res = await methods.NewInvoice({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
const res = await methods.NewInvoice({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
|
||||||
opStats.handle = process.hrtime.bigint()
|
opStats.handle = process.hrtime.bigint()
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
|
|
@ -405,7 +424,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.DecodeInvoiceRequestValidate(operation.req)
|
const error = Types.DecodeInvoiceRequestValidate(operation.req)
|
||||||
opStats.validate = process.hrtime.bigint()
|
opStats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) throw error
|
if (error !== null) throw error
|
||||||
const res = await methods.DecodeInvoice({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
const res = await methods.DecodeInvoice({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
|
||||||
opStats.handle = process.hrtime.bigint()
|
opStats.handle = process.hrtime.bigint()
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
|
|
@ -417,7 +436,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.PayInvoiceRequestValidate(operation.req)
|
const error = Types.PayInvoiceRequestValidate(operation.req)
|
||||||
opStats.validate = process.hrtime.bigint()
|
opStats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) throw error
|
if (error !== null) throw error
|
||||||
const res = await methods.PayInvoice({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
const res = await methods.PayInvoice({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
|
||||||
opStats.handle = process.hrtime.bigint()
|
opStats.handle = process.hrtime.bigint()
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
|
|
@ -429,7 +448,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
const error = Types.OpenChannelRequestValidate(operation.req)
|
const error = Types.OpenChannelRequestValidate(operation.req)
|
||||||
opStats.validate = process.hrtime.bigint()
|
opStats.validate = process.hrtime.bigint()
|
||||||
if (error !== null) throw error
|
if (error !== null) throw error
|
||||||
const res = await methods.OpenChannel({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
const res = await methods.OpenChannel({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
|
||||||
opStats.handle = process.hrtime.bigint()
|
opStats.handle = process.hrtime.bigint()
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
|
|
@ -439,7 +458,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
throw new Error('method not defined: GetLnurlWithdrawLink')
|
throw new Error('method not defined: GetLnurlWithdrawLink')
|
||||||
} else {
|
} else {
|
||||||
opStats.validate = opStats.guard
|
opStats.validate = opStats.guard
|
||||||
const res = await methods.GetLnurlWithdrawLink({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
const res = await methods.GetLnurlWithdrawLink({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
|
||||||
opStats.handle = process.hrtime.bigint()
|
opStats.handle = process.hrtime.bigint()
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
|
|
@ -449,7 +468,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
throw new Error('method not defined: GetLnurlPayLink')
|
throw new Error('method not defined: GetLnurlPayLink')
|
||||||
} else {
|
} else {
|
||||||
opStats.validate = opStats.guard
|
opStats.validate = opStats.guard
|
||||||
const res = await methods.GetLnurlPayLink({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
const res = await methods.GetLnurlPayLink({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
|
||||||
opStats.handle = process.hrtime.bigint()
|
opStats.handle = process.hrtime.bigint()
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
|
|
@ -459,7 +478,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
throw new Error('method not defined: GetLNURLChannelLink')
|
throw new Error('method not defined: GetLNURLChannelLink')
|
||||||
} else {
|
} else {
|
||||||
opStats.validate = opStats.guard
|
opStats.validate = opStats.guard
|
||||||
const res = await methods.GetLNURLChannelLink({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
const res = await methods.GetLNURLChannelLink({ ...operation, ctx }); responses.push({ status: 'OK', ...res })
|
||||||
opStats.handle = process.hrtime.bigint()
|
opStats.handle = process.hrtime.bigint()
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
|
|
@ -467,14 +486,14 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
default:
|
default:
|
||||||
throw new Error('unkown rpcName')
|
throw new Error('unkown rpcName')
|
||||||
}
|
}
|
||||||
} catch(ex) {const e = ex as any; logger.error(e.message || e); callsMetrics.push({ ...opInfo, ...opStats, ...ctx, error: e.message }); responses.push({ status: 'ERROR', reason: e.message || e })}
|
} catch (ex) { const e = ex as any; logger.error(e.message || e); callsMetrics.push({ ...opInfo, ...opStats, ...ctx, error: e.message }); responses.push({ status: 'ERROR', reason: e.message || e }) }
|
||||||
}
|
}
|
||||||
stats.handle = process.hrtime.bigint()
|
stats.handle = process.hrtime.bigint()
|
||||||
res({ status: 'OK', responses })
|
res({ status: 'OK', responses })
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...ctx }, ...callsMetrics])
|
opts.metricsCallback([{ ...info, ...stats, ...ctx }, ...callsMetrics])
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
default: logger.error('unknown rpc call name from nostr event:'+req.rpcName)
|
default: logger.error('unknown rpc call name from nostr event:' + req.rpcName)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -369,6 +369,12 @@ service LightningPub {
|
||||||
option (http_route) = "/api/user/migrations/sub";
|
option (http_route) = "/api/user/migrations/sub";
|
||||||
option (nostr) = true;
|
option (nostr) = true;
|
||||||
}
|
}
|
||||||
|
rpc GetHttpCreds(structs.Empty) returns (stream structs.HttpCreds){
|
||||||
|
option (auth_type) = "User";
|
||||||
|
option (http_method) = "post";
|
||||||
|
option (http_route) = "/api/user/http_creds";
|
||||||
|
option (nostr) = true;
|
||||||
|
}
|
||||||
rpc BatchUser(structs.Empty) returns (structs.Empty){
|
rpc BatchUser(structs.Empty) returns (structs.Empty){
|
||||||
option (auth_type) = "User";
|
option (auth_type) = "User";
|
||||||
option (http_method) = "post";
|
option (http_method) = "post";
|
||||||
|
|
|
||||||
|
|
@ -443,3 +443,7 @@ message LinkNPubThroughTokenRequest {
|
||||||
string nostr_pub = 2;
|
string nostr_pub = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message HttpCreds {
|
||||||
|
string url = 1;
|
||||||
|
string token = 2;
|
||||||
|
}
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 94 KiB |
|
|
@ -3,12 +3,11 @@ import path from 'path';
|
||||||
import { ServerOptions } from "../proto/autogenerated/ts/express_server";
|
import { ServerOptions } from "../proto/autogenerated/ts/express_server";
|
||||||
import { AdminContext, MetricsContext } from "../proto/autogenerated/ts/types";
|
import { AdminContext, MetricsContext } from "../proto/autogenerated/ts/types";
|
||||||
import Main from './services/main'
|
import Main from './services/main'
|
||||||
import { getLogger } from './services/helpers/logger.js'
|
import { ERROR, getLogger } from './services/helpers/logger.js'
|
||||||
|
|
||||||
const serverOptions = (mainHandler: Main): ServerOptions => {
|
const serverOptions = (mainHandler: Main): ServerOptions => {
|
||||||
const log = getLogger({})
|
const log = getLogger({})
|
||||||
return {
|
return {
|
||||||
logger: { log, error: err => log("ERROR", err) },
|
logger: { log, error: err => log(ERROR, err) },
|
||||||
staticFiles: path.resolve('static'),
|
staticFiles: path.resolve('static'),
|
||||||
AdminAuthGuard: adminAuth,
|
AdminAuthGuard: adminAuth,
|
||||||
MetricsAuthGuard: metricsAuth,
|
MetricsAuthGuard: metricsAuth,
|
||||||
|
|
|
||||||
|
|
@ -16,11 +16,15 @@ const start = async () => {
|
||||||
log("manual process ended")
|
log("manual process ended")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const { apps, mainHandler } = keepOn
|
const { apps, mainHandler, liquidityProviderInfo } = keepOn
|
||||||
const serverMethods = GetServerMethods(mainHandler)
|
const serverMethods = GetServerMethods(mainHandler)
|
||||||
const nostrSettings = LoadNosrtSettingsFromEnv()
|
const nostrSettings = LoadNosrtSettingsFromEnv()
|
||||||
const { Send } = nostrMiddleware(serverMethods, mainHandler, { ...nostrSettings, apps })
|
const { Send } = nostrMiddleware(serverMethods, mainHandler,
|
||||||
|
{ ...nostrSettings, apps, clients: [liquidityProviderInfo] },
|
||||||
|
(e, p) => mainHandler.liquidProvider.onEvent(e, p)
|
||||||
|
)
|
||||||
mainHandler.attachNostrSend(Send)
|
mainHandler.attachNostrSend(Send)
|
||||||
|
mainHandler.StartBeacons()
|
||||||
const Server = NewServer(serverMethods, serverOptions(mainHandler))
|
const Server = NewServer(serverMethods, serverOptions(mainHandler))
|
||||||
Server.Listen(mainSettings.servicePort)
|
Server.Listen(mainSettings.servicePort)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,9 +3,9 @@ import Nostr from "./services/nostr/index.js"
|
||||||
import { NostrSend, NostrSettings } from "./services/nostr/handler.js"
|
import { NostrSend, NostrSettings } from "./services/nostr/handler.js"
|
||||||
import * as Types from '../proto/autogenerated/ts/types.js'
|
import * as Types from '../proto/autogenerated/ts/types.js'
|
||||||
import NewNostrTransport, { NostrRequest } from '../proto/autogenerated/ts/nostr_transport.js';
|
import NewNostrTransport, { NostrRequest } from '../proto/autogenerated/ts/nostr_transport.js';
|
||||||
import { getLogger } from "./services/helpers/logger.js";
|
import { ERROR, getLogger } from "./services/helpers/logger.js";
|
||||||
|
|
||||||
export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSettings: NostrSettings): { Stop: () => void, Send: NostrSend } => {
|
export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSettings: NostrSettings, onClientEvent: (e: { requestId: string }, fromPub: string) => void): { Stop: () => void, Send: NostrSend } => {
|
||||||
const log = getLogger({})
|
const log = getLogger({})
|
||||||
const nostrTransport = NewNostrTransport(serverMethods, {
|
const nostrTransport = NewNostrTransport(serverMethods, {
|
||||||
NostrUserAuthGuard: async (appId, pub) => {
|
NostrUserAuthGuard: async (appId, pub) => {
|
||||||
|
|
@ -14,7 +14,7 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett
|
||||||
return { user_id: nostrUser.user.user_id, app_user_id: nostrUser.identifier, app_id: appId || "" }
|
return { user_id: nostrUser.user.user_id, app_user_id: nostrUser.identifier, app_id: appId || "" }
|
||||||
},
|
},
|
||||||
metricsCallback: metrics => mainHandler.settings.recordPerformance ? mainHandler.metricsManager.AddMetrics(metrics) : null,
|
metricsCallback: metrics => mainHandler.settings.recordPerformance ? mainHandler.metricsManager.AddMetrics(metrics) : null,
|
||||||
logger: { log: console.log, error: err => log("ERROR", err) }
|
logger: { log: console.log, error: err => log(ERROR, err) }
|
||||||
})
|
})
|
||||||
const nostr = new Nostr(nostrSettings, event => {
|
const nostr = new Nostr(nostrSettings, event => {
|
||||||
let j: NostrRequest
|
let j: NostrRequest
|
||||||
|
|
@ -22,11 +22,19 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett
|
||||||
j = JSON.parse(event.content)
|
j = JSON.parse(event.content)
|
||||||
log("nostr event", j.rpcName || 'no rpc name')
|
log("nostr event", j.rpcName || 'no rpc name')
|
||||||
} catch {
|
} catch {
|
||||||
log("ERROR", "invalid json event received", event.content)
|
log(ERROR, "invalid json event received", event.content)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!j.rpcName) {
|
||||||
|
onClientEvent(j as { requestId: string }, event.pub)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (j.authIdentifier !== event.pub) {
|
||||||
|
log(ERROR, "authIdentifier does not match", j.authIdentifier || "--", event.pub)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
nostrTransport({ ...j, appId: event.appId }, res => {
|
nostrTransport({ ...j, appId: event.appId }, res => {
|
||||||
nostr.Send(event.appId, { type: 'content', pub: event.pub, content: JSON.stringify({ ...res, requestId: j.requestId }) })
|
nostr.Send({ type: 'app', appId: event.appId }, { type: 'content', pub: event.pub, content: JSON.stringify({ ...res, requestId: j.requestId }) })
|
||||||
}, event.startAtNano, event.startAtMs)
|
}, event.startAtNano, event.startAtMs)
|
||||||
})
|
})
|
||||||
return { Stop: () => nostr.Stop, Send: (...args) => nostr.Send(...args) }
|
return { Stop: () => nostr.Stop, Send: (...args) => nostr.Send(...args) }
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ export default class FunctionQueue<T> {
|
||||||
running: boolean = false
|
running: boolean = false
|
||||||
f: () => Promise<T>
|
f: () => Promise<T>
|
||||||
constructor(name: string, f: () => Promise<T>) {
|
constructor(name: string, f: () => Promise<T>) {
|
||||||
this.log = getLogger({ appName: name })
|
this.log = getLogger({ component: name })
|
||||||
this.f = f
|
this.f = f
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,37 +1,74 @@
|
||||||
import fs from 'fs'
|
import fs from 'fs'
|
||||||
type LoggerParams = { appName?: string, userId?: string }
|
export const DEBUG = Symbol("DEBUG")
|
||||||
export type PubLogger = (...message: (string | number | object)[]) => void
|
export const ERROR = Symbol("ERROR")
|
||||||
|
export const WARN = Symbol("WARN")
|
||||||
|
type LoggerParams = { appName?: string, userId?: string, component?: string }
|
||||||
|
export type PubLogger = (...message: (string | number | object | symbol)[]) => void
|
||||||
type Writer = (message: string) => void
|
type Writer = (message: string) => void
|
||||||
|
const logsDir = process.env.LOGS_DIR || "logs"
|
||||||
|
const logLevel = process.env.LOG_LEVEL || "DEBUG"
|
||||||
try {
|
try {
|
||||||
fs.mkdirSync("logs")
|
fs.mkdirSync(logsDir)
|
||||||
} catch { }
|
} catch { }
|
||||||
|
if (logLevel !== "DEBUG" && logLevel !== "WARN" && logLevel !== "ERROR") {
|
||||||
|
throw new Error("Invalid log level " + logLevel + " must be one of (DEBUG, WARN, ERROR)")
|
||||||
|
}
|
||||||
const z = (n: number) => n < 10 ? `0${n}` : `${n}`
|
const z = (n: number) => n < 10 ? `0${n}` : `${n}`
|
||||||
const openWriter = (fileName: string): Writer => {
|
const openWriter = (fileName: string): Writer => {
|
||||||
const logStream = fs.createWriteStream(`logs/${fileName}`, { flags: 'a' });
|
const now = new Date()
|
||||||
|
const date = `${now.getFullYear()}-${z(now.getMonth() + 1)}-${z(now.getDate())}`
|
||||||
|
const logStream = fs.createWriteStream(`${logsDir}/${fileName}_${date}.log`, { flags: 'a' });
|
||||||
return (message) => {
|
return (message) => {
|
||||||
logStream.write(message + "\n")
|
logStream.write(message + "\n")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const rootWriter = openWriter("ROOT.log")
|
const rootWriter = openWriter("ROOT.log")
|
||||||
if (!fs.existsSync("logs/apps")) {
|
if (!fs.existsSync(`${logsDir}/apps`)) {
|
||||||
fs.mkdirSync("logs/apps", { recursive: true });
|
fs.mkdirSync(`${logsDir}/apps`, { recursive: true });
|
||||||
}
|
}
|
||||||
if (!fs.existsSync("logs/users")) {
|
if (!fs.existsSync(`${logsDir}/users`)) {
|
||||||
fs.mkdirSync("logs/users", { recursive: true });
|
fs.mkdirSync(`${logsDir}/users`, { recursive: true });
|
||||||
|
}
|
||||||
|
if (!fs.existsSync(`${logsDir}/components`)) {
|
||||||
|
fs.mkdirSync(`${logsDir}/components`, { recursive: true });
|
||||||
}
|
}
|
||||||
export const getLogger = (params: LoggerParams): PubLogger => {
|
export const getLogger = (params: LoggerParams): PubLogger => {
|
||||||
const writers: Writer[] = []
|
const writers: Writer[] = []
|
||||||
if (params.appName) {
|
if (params.appName) {
|
||||||
writers.push(openWriter(`apps/${params.appName}.log`))
|
writers.push(openWriter(`apps/${params.appName}`))
|
||||||
}
|
}
|
||||||
if (params.userId) {
|
if (params.userId) {
|
||||||
writers.push(openWriter(`users/${params.userId}.log`))
|
writers.push(openWriter(`users/${params.userId}`))
|
||||||
|
}
|
||||||
|
if (params.component) {
|
||||||
|
writers.push(openWriter(`components/${params.component}`))
|
||||||
}
|
}
|
||||||
if (writers.length === 0) {
|
if (writers.length === 0) {
|
||||||
writers.push(rootWriter)
|
writers.push(rootWriter)
|
||||||
}
|
}
|
||||||
|
|
||||||
return (...message) => {
|
return (...message) => {
|
||||||
|
switch (message[0]) {
|
||||||
|
case DEBUG:
|
||||||
|
if (logLevel !== "DEBUG") {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
message[0] = "DEBUG"
|
||||||
|
break;
|
||||||
|
case WARN:
|
||||||
|
if (logLevel === "ERROR") {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
message[0] = "WARN"
|
||||||
|
break;
|
||||||
|
case ERROR:
|
||||||
|
message[0] = "ERROR"
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
if (logLevel !== "DEBUG") {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
const now = new Date()
|
const now = new Date()
|
||||||
const timestamp = `${now.getFullYear()}-${z(now.getMonth() + 1)}-${z(now.getDate())} ${z(now.getHours())}:${z(now.getMinutes())}:${z(now.getSeconds())}`
|
const timestamp = `${now.getFullYear()}-${z(now.getMonth() + 1)}-${z(now.getDate())} ${z(now.getHours())}:${z(now.getMinutes())}:${z(now.getSeconds())}`
|
||||||
const toLog = [timestamp]
|
const toLog = [timestamp]
|
||||||
|
|
@ -41,6 +78,12 @@ export const getLogger = (params: LoggerParams): PubLogger => {
|
||||||
}
|
}
|
||||||
toLog.push(params.appName)
|
toLog.push(params.appName)
|
||||||
}
|
}
|
||||||
|
if (params.component) {
|
||||||
|
if (disabledComponents.includes(params.component)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
toLog.push(params.component)
|
||||||
|
}
|
||||||
if (params.userId) {
|
if (params.userId) {
|
||||||
toLog.push(params.userId)
|
toLog.push(params.userId)
|
||||||
}
|
}
|
||||||
|
|
@ -50,7 +93,13 @@ export const getLogger = (params: LoggerParams): PubLogger => {
|
||||||
writers.forEach(w => w(final))
|
writers.forEach(w => w(final))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const disabledApps: string[] = []
|
let disabledApps: string[] = []
|
||||||
export const disableLoggers = (appNamesToDisable: string[]) => {
|
let disabledComponents: string[] = []
|
||||||
disabledApps.push(...appNamesToDisable)
|
export const resetDisabledLoggers = () => {
|
||||||
|
disabledApps = []
|
||||||
|
disabledComponents = []
|
||||||
|
}
|
||||||
|
export const disableLoggers = (appNamesToDisable: string[], componentsToDisable: string[]) => {
|
||||||
|
disabledApps.push(...appNamesToDisable)
|
||||||
|
disabledComponents.push(...componentsToDisable)
|
||||||
}
|
}
|
||||||
|
|
@ -1,11 +1,22 @@
|
||||||
import { EnvMustBeNonEmptyString, EnvMustBeInteger, EnvCanBeBoolean } from '../helpers/envParser.js'
|
import { EnvMustBeNonEmptyString, EnvMustBeInteger, EnvCanBeBoolean, EnvCanBeInteger } from '../helpers/envParser.js'
|
||||||
import { LndSettings } from './settings.js'
|
import { LndSettings } from './settings.js'
|
||||||
export const LoadLndSettingsFromEnv = (): LndSettings => {
|
import os from 'os'
|
||||||
const lndAddr = EnvMustBeNonEmptyString("LND_ADDRESS")
|
import path from 'path'
|
||||||
const lndCertPath = EnvMustBeNonEmptyString("LND_CERT_PATH")
|
|
||||||
const lndMacaroonPath = EnvMustBeNonEmptyString("LND_MACAROON_PATH")
|
const resolveHome = (filepath: string) => {
|
||||||
const feeRateLimit = EnvMustBeInteger("OUTBOUND_MAX_FEE_BPS") / 10000
|
if (filepath[0] === '~') {
|
||||||
const feeFixedLimit = EnvMustBeInteger("OUTBOUND_MAX_FEE_EXTRA_SATS")
|
return path.join(os.homedir(), filepath.slice(1))
|
||||||
const mockLnd = EnvCanBeBoolean("MOCK_LND")
|
}
|
||||||
return { mainNode: { lndAddr, lndCertPath, lndMacaroonPath }, feeRateLimit, feeFixedLimit, mockLnd }
|
return filepath
|
||||||
|
}
|
||||||
|
|
||||||
|
export const LoadLndSettingsFromEnv = (): LndSettings => {
|
||||||
|
const lndAddr = process.env.LND_ADDRESS || "127.0.0.1:10009"
|
||||||
|
const lndCertPath = process.env.LND_CERT_PATH || resolveHome("~/.lnd/tls.cert")
|
||||||
|
const lndMacaroonPath = process.env.LND_MACAROON_PATH || resolveHome("~/.lnd/data/chain/bitcoin/mainnet/admin.macaroon")
|
||||||
|
const feeRateLimit = EnvCanBeInteger("OUTBOUND_MAX_FEE_BPS", 60) / 10000
|
||||||
|
const feeFixedLimit = EnvCanBeInteger("OUTBOUND_MAX_FEE_EXTRA_SATS", 100)
|
||||||
|
const mockLnd = EnvCanBeBoolean("MOCK_LND")
|
||||||
|
const liquidityProviderPub = process.env.LIQUIDITY_PROVIDER_PUB || ""
|
||||||
|
return { mainNode: { lndAddr, lndCertPath, lndMacaroonPath }, feeRateLimit, feeFixedLimit, mockLnd, liquidityProviderPub, useOnlyLiquidityProvider: false }
|
||||||
}
|
}
|
||||||
|
|
|
||||||
226
src/services/lnd/liquidityProvider.ts
Normal file
226
src/services/lnd/liquidityProvider.ts
Normal file
|
|
@ -0,0 +1,226 @@
|
||||||
|
import newNostrClient from '../../../proto/autogenerated/ts/nostr_client.js'
|
||||||
|
import { NostrRequest } from '../../../proto/autogenerated/ts/nostr_transport.js'
|
||||||
|
import * as Types from '../../../proto/autogenerated/ts/types.js'
|
||||||
|
import { decodeNprofile } from '../../custom-nip19.js'
|
||||||
|
import { getLogger } from '../helpers/logger.js'
|
||||||
|
import { NostrEvent, NostrSend } from '../nostr/handler.js'
|
||||||
|
import { relayInit } from '../nostr/tools/relay.js'
|
||||||
|
import { InvoicePaidCb } from './settings.js'
|
||||||
|
|
||||||
|
export type LiquidityRequest = { action: 'spend' | 'receive', amount: number }
|
||||||
|
|
||||||
|
export type nostrCallback<T> = { startedAtMillis: number, type: 'single' | 'stream', f: (res: T) => void }
|
||||||
|
export class LiquidityProvider {
|
||||||
|
client: ReturnType<typeof newNostrClient>
|
||||||
|
clientCbs: Record<string, nostrCallback<any>> = {}
|
||||||
|
clientId: string = ""
|
||||||
|
myPub: string = ""
|
||||||
|
log = getLogger({ component: 'liquidityProvider' })
|
||||||
|
nostrSend: NostrSend | null = null
|
||||||
|
ready = false
|
||||||
|
pubDestination: string
|
||||||
|
latestMaxWithdrawable: number | null = null
|
||||||
|
invoicePaidCb: InvoicePaidCb
|
||||||
|
connecting = false
|
||||||
|
readyInterval: NodeJS.Timeout
|
||||||
|
// make the sub process accept client
|
||||||
|
constructor(pubDestination: string, invoicePaidCb: InvoicePaidCb) {
|
||||||
|
if (!pubDestination) {
|
||||||
|
this.log("No pub provider to liquidity provider, will not be initialized")
|
||||||
|
}
|
||||||
|
this.pubDestination = pubDestination
|
||||||
|
this.invoicePaidCb = invoicePaidCb
|
||||||
|
this.client = newNostrClient({
|
||||||
|
pubDestination: this.pubDestination,
|
||||||
|
retrieveNostrUserAuth: async () => this.myPub,
|
||||||
|
}, this.clientSend, this.clientSub)
|
||||||
|
|
||||||
|
this.readyInterval = setInterval(() => {
|
||||||
|
if (this.ready) {
|
||||||
|
clearInterval(this.readyInterval)
|
||||||
|
this.Connect()
|
||||||
|
}
|
||||||
|
}, 1000)
|
||||||
|
}
|
||||||
|
|
||||||
|
Stop = () => {
|
||||||
|
clearInterval(this.readyInterval)
|
||||||
|
}
|
||||||
|
|
||||||
|
Connect = async () => {
|
||||||
|
await new Promise(res => setTimeout(res, 2000))
|
||||||
|
this.log("ready")
|
||||||
|
await this.CheckUserState()
|
||||||
|
if (this.latestMaxWithdrawable === null) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.log("subbing to user operations")
|
||||||
|
this.client.GetLiveUserOperations(res => {
|
||||||
|
console.log("got user operation", res)
|
||||||
|
if (res.status === 'ERROR') {
|
||||||
|
this.log("error getting user operations", res.reason)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.log("got user operation", res.operation)
|
||||||
|
if (res.operation.type === Types.UserOperationType.INCOMING_INVOICE) {
|
||||||
|
this.log("invoice was paid", res.operation.identifier)
|
||||||
|
this.invoicePaidCb(res.operation.identifier, res.operation.amount, false)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
CheckUserState = async () => {
|
||||||
|
const res = await this.client.GetUserInfo()
|
||||||
|
if (res.status === 'ERROR') {
|
||||||
|
this.log("error getting user info", res)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.latestMaxWithdrawable = res.max_withdrawable
|
||||||
|
this.log("latest provider balance:", res.max_withdrawable)
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
CanProviderHandle = (req: LiquidityRequest) => {
|
||||||
|
if (this.latestMaxWithdrawable === null) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (req.action === 'spend') {
|
||||||
|
return this.latestMaxWithdrawable > req.amount
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
AddInvoice = async (amount: number, memo: string) => {
|
||||||
|
const res = await this.client.NewInvoice({ amountSats: amount, memo })
|
||||||
|
if (res.status === 'ERROR') {
|
||||||
|
this.log("error creating invoice", res.reason)
|
||||||
|
throw new Error(res.reason)
|
||||||
|
}
|
||||||
|
this.log("new invoice", res.invoice)
|
||||||
|
this.CheckUserState()
|
||||||
|
return res.invoice
|
||||||
|
}
|
||||||
|
|
||||||
|
PayInvoice = async (invoice: string) => {
|
||||||
|
const res = await this.client.PayInvoice({ invoice, amount: 0 })
|
||||||
|
if (res.status === 'ERROR') {
|
||||||
|
this.log("error paying invoice", res.reason)
|
||||||
|
throw new Error(res.reason)
|
||||||
|
}
|
||||||
|
this.log("paid invoice", res)
|
||||||
|
this.CheckUserState()
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
setNostrInfo = ({ clientId, myPub }: { myPub: string, clientId: string }) => {
|
||||||
|
this.clientId = clientId
|
||||||
|
this.myPub = myPub
|
||||||
|
this.setSetIfReady()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
attachNostrSend(f: NostrSend) {
|
||||||
|
this.nostrSend = f
|
||||||
|
this.setSetIfReady()
|
||||||
|
}
|
||||||
|
|
||||||
|
setSetIfReady = () => {
|
||||||
|
if (this.nostrSend && !!this.pubDestination && !!this.clientId && !!this.myPub) {
|
||||||
|
this.ready = true
|
||||||
|
this.log("ready to send to ", this.pubDestination)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onEvent = async (res: { requestId: string }, fromPub: string) => {
|
||||||
|
if (fromPub !== this.pubDestination) {
|
||||||
|
this.log("got event from invalid pub", fromPub, this.pubDestination)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (this.clientCbs[res.requestId]) {
|
||||||
|
const cb = this.clientCbs[res.requestId]
|
||||||
|
cb.f(res)
|
||||||
|
if (cb.type === 'single') {
|
||||||
|
delete this.clientCbs[res.requestId]
|
||||||
|
this.log(this.getSingleSubs(), "single subs left")
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
clientSend = (to: string, message: NostrRequest): Promise<any> => {
|
||||||
|
if (!this.ready || !this.nostrSend) {
|
||||||
|
throw new Error("liquidity provider not initialized")
|
||||||
|
}
|
||||||
|
if (!message.requestId) {
|
||||||
|
message.requestId = makeId(16)
|
||||||
|
}
|
||||||
|
const reqId = message.requestId
|
||||||
|
if (this.clientCbs[reqId]) {
|
||||||
|
throw new Error("request was already sent")
|
||||||
|
}
|
||||||
|
this.nostrSend({ type: 'client', clientId: this.clientId }, {
|
||||||
|
type: 'content',
|
||||||
|
pub: to,
|
||||||
|
content: JSON.stringify(message)
|
||||||
|
})
|
||||||
|
|
||||||
|
//this.nostrSend(this.relays, to, JSON.stringify(message), this.settings)
|
||||||
|
|
||||||
|
this.log("subbing to single send", reqId, message.rpcName || 'no rpc name')
|
||||||
|
return new Promise(res => {
|
||||||
|
this.clientCbs[reqId] = {
|
||||||
|
startedAtMillis: Date.now(),
|
||||||
|
type: 'single',
|
||||||
|
f: (response: any) => { res(response) },
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
clientSub = (to: string, message: NostrRequest, cb: (res: any) => void): void => {
|
||||||
|
if (!this.ready || !this.nostrSend) {
|
||||||
|
throw new Error("liquidity provider not initialized")
|
||||||
|
}
|
||||||
|
if (!message.requestId) {
|
||||||
|
message.requestId = message.rpcName
|
||||||
|
}
|
||||||
|
const reqId = message.requestId
|
||||||
|
if (!reqId) {
|
||||||
|
throw new Error("invalid sub")
|
||||||
|
}
|
||||||
|
if (this.clientCbs[reqId]) {
|
||||||
|
this.clientCbs[reqId] = {
|
||||||
|
startedAtMillis: Date.now(),
|
||||||
|
type: 'stream',
|
||||||
|
f: (response: any) => { cb(response) },
|
||||||
|
}
|
||||||
|
this.log("sub for", reqId, "was already registered, overriding")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.nostrSend({ type: 'client', clientId: this.clientId }, {
|
||||||
|
type: 'content',
|
||||||
|
pub: to,
|
||||||
|
content: JSON.stringify(message)
|
||||||
|
})
|
||||||
|
this.log("subbing to stream", reqId)
|
||||||
|
this.clientCbs[reqId] = {
|
||||||
|
startedAtMillis: Date.now(),
|
||||||
|
type: 'stream',
|
||||||
|
f: (response: any) => { cb(response) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
getSingleSubs = () => {
|
||||||
|
return Object.entries(this.clientCbs).filter(([_, cb]) => cb.type === 'single')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const makeId = (length: number) => {
|
||||||
|
let result = '';
|
||||||
|
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||||||
|
const charactersLength = characters.length;
|
||||||
|
for (let i = 0; i < length; i++) {
|
||||||
|
result += characters.charAt(Math.floor(Math.random() * charactersLength));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
@ -16,6 +16,7 @@ import { SendCoinsReq } from './sendCoinsReq.js';
|
||||||
import { LndSettings, AddressPaidCb, InvoicePaidCb, NodeInfo, Invoice, DecodedInvoice, PaidInvoice, NewBlockCb, HtlcCb, BalanceInfo } from './settings.js';
|
import { LndSettings, AddressPaidCb, InvoicePaidCb, NodeInfo, Invoice, DecodedInvoice, PaidInvoice, NewBlockCb, HtlcCb, BalanceInfo } from './settings.js';
|
||||||
import { getLogger } from '../helpers/logger.js';
|
import { getLogger } from '../helpers/logger.js';
|
||||||
import { HtlcEvent_EventType } from '../../../proto/lnd/router.js';
|
import { HtlcEvent_EventType } from '../../../proto/lnd/router.js';
|
||||||
|
import { LiquidityProvider, LiquidityRequest } from './liquidityProvider.js';
|
||||||
const DeadLineMetadata = (deadline = 10 * 1000) => ({ deadline: Date.now() + deadline })
|
const DeadLineMetadata = (deadline = 10 * 1000) => ({ deadline: Date.now() + deadline })
|
||||||
const deadLndRetrySeconds = 5
|
const deadLndRetrySeconds = 5
|
||||||
export default class {
|
export default class {
|
||||||
|
|
@ -32,9 +33,10 @@ export default class {
|
||||||
invoicePaidCb: InvoicePaidCb
|
invoicePaidCb: InvoicePaidCb
|
||||||
newBlockCb: NewBlockCb
|
newBlockCb: NewBlockCb
|
||||||
htlcCb: HtlcCb
|
htlcCb: HtlcCb
|
||||||
log = getLogger({ appName: 'lndManager' })
|
log = getLogger({ component: 'lndManager' })
|
||||||
outgoingOpsLocked = false
|
outgoingOpsLocked = false
|
||||||
constructor(settings: LndSettings, addressPaidCb: AddressPaidCb, invoicePaidCb: InvoicePaidCb, newBlockCb: NewBlockCb, htlcCb: HtlcCb) {
|
liquidProvider: LiquidityProvider
|
||||||
|
constructor(settings: LndSettings, liquidProvider: LiquidityProvider, addressPaidCb: AddressPaidCb, invoicePaidCb: InvoicePaidCb, newBlockCb: NewBlockCb, htlcCb: HtlcCb) {
|
||||||
this.settings = settings
|
this.settings = settings
|
||||||
this.addressPaidCb = addressPaidCb
|
this.addressPaidCb = addressPaidCb
|
||||||
this.invoicePaidCb = invoicePaidCb
|
this.invoicePaidCb = invoicePaidCb
|
||||||
|
|
@ -60,6 +62,7 @@ export default class {
|
||||||
this.invoices = new InvoicesClient(transport)
|
this.invoices = new InvoicesClient(transport)
|
||||||
this.router = new RouterClient(transport)
|
this.router = new RouterClient(transport)
|
||||||
this.chainNotifier = new ChainNotifierClient(transport)
|
this.chainNotifier = new ChainNotifierClient(transport)
|
||||||
|
this.liquidProvider = liquidProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
LockOutgoingOperations(): void {
|
LockOutgoingOperations(): void {
|
||||||
|
|
@ -74,6 +77,22 @@ export default class {
|
||||||
}
|
}
|
||||||
Stop() {
|
Stop() {
|
||||||
this.abortController.abort()
|
this.abortController.abort()
|
||||||
|
this.liquidProvider.Stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
async ShouldUseLiquidityProvider(req: LiquidityRequest): Promise<boolean> {
|
||||||
|
if (this.settings.useOnlyLiquidityProvider) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if (!this.liquidProvider.CanProviderHandle(req)) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
const channels = await this.ListChannels()
|
||||||
|
if (channels.channels.length === 0) {
|
||||||
|
this.log("no channels, will use liquidity provider")
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
async Warmup() {
|
async Warmup() {
|
||||||
this.SubscribeAddressPaid()
|
this.SubscribeAddressPaid()
|
||||||
|
|
@ -212,7 +231,7 @@ export default class {
|
||||||
}, { abort: this.abortController.signal })
|
}, { abort: this.abortController.signal })
|
||||||
stream.responses.onMessage(invoice => {
|
stream.responses.onMessage(invoice => {
|
||||||
if (invoice.state === Invoice_InvoiceState.SETTLED) {
|
if (invoice.state === Invoice_InvoiceState.SETTLED) {
|
||||||
this.log("An invoice was paid for", Number(invoice.amtPaidSat), "sats")
|
this.log("An invoice was paid for", Number(invoice.amtPaidSat), "sats", invoice.paymentRequest)
|
||||||
this.latestKnownSettleIndex = Number(invoice.settleIndex)
|
this.latestKnownSettleIndex = Number(invoice.settleIndex)
|
||||||
this.invoicePaidCb(invoice.paymentRequest, Number(invoice.amtPaidSat), false)
|
this.invoicePaidCb(invoice.paymentRequest, Number(invoice.amtPaidSat), false)
|
||||||
}
|
}
|
||||||
|
|
@ -251,6 +270,11 @@ export default class {
|
||||||
async NewInvoice(value: number, memo: string, expiry: number): Promise<Invoice> {
|
async NewInvoice(value: number, memo: string, expiry: number): Promise<Invoice> {
|
||||||
this.log("generating new invoice for", value, "sats")
|
this.log("generating new invoice for", value, "sats")
|
||||||
await this.Health()
|
await this.Health()
|
||||||
|
const shouldUseLiquidityProvider = await this.ShouldUseLiquidityProvider({ action: 'receive', amount: value })
|
||||||
|
if (shouldUseLiquidityProvider) {
|
||||||
|
const invoice = await this.liquidProvider.AddInvoice(value, memo)
|
||||||
|
return { payRequest: invoice }
|
||||||
|
}
|
||||||
const res = await this.lightning.addInvoice(AddInvoiceReq(value, expiry, false, memo), DeadLineMetadata())
|
const res = await this.lightning.addInvoice(AddInvoiceReq(value, expiry, false, memo), DeadLineMetadata())
|
||||||
this.log("new invoice", res.response.paymentRequest)
|
this.log("new invoice", res.response.paymentRequest)
|
||||||
return { payRequest: res.response.paymentRequest }
|
return { payRequest: res.response.paymentRequest }
|
||||||
|
|
@ -281,6 +305,11 @@ export default class {
|
||||||
}
|
}
|
||||||
await this.Health()
|
await this.Health()
|
||||||
this.log("paying invoice", invoice, "for", amount, "sats")
|
this.log("paying invoice", invoice, "for", amount, "sats")
|
||||||
|
const shouldUseLiquidityProvider = await this.ShouldUseLiquidityProvider({ action: 'spend', amount })
|
||||||
|
if (shouldUseLiquidityProvider) {
|
||||||
|
const res = await this.liquidProvider.PayInvoice(invoice)
|
||||||
|
return { feeSat: res.network_fee + res.service_fee, valueSat: res.amount_paid, paymentPreimage: res.preimage }
|
||||||
|
}
|
||||||
const abortController = new AbortController()
|
const abortController = new AbortController()
|
||||||
const req = PayInvoiceReq(invoice, amount, feeLimit)
|
const req = PayInvoiceReq(invoice, amount, feeLimit)
|
||||||
const stream = this.router.sendPaymentV2(req, { abort: abortController.signal })
|
const stream = this.router.sendPaymentV2(req, { abort: abortController.signal })
|
||||||
|
|
@ -298,7 +327,7 @@ export default class {
|
||||||
return
|
return
|
||||||
case Payment_PaymentStatus.SUCCEEDED:
|
case Payment_PaymentStatus.SUCCEEDED:
|
||||||
this.log("invoice payment succeded", Number(payment.valueSat))
|
this.log("invoice payment succeded", Number(payment.valueSat))
|
||||||
res({ feeSat: Number(payment.feeSat), valueSat: Number(payment.valueSat), paymentPreimage: payment.paymentPreimage })
|
res({ feeSat: Math.ceil(Number(payment.feeMsat) / 1000), valueSat: Number(payment.valueSat), paymentPreimage: payment.paymentPreimage })
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
29
src/services/lnd/lsp.ts
Normal file
29
src/services/lnd/lsp.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
import fetch from "node-fetch"
|
||||||
|
|
||||||
|
export class LSP {
|
||||||
|
serviceUrl: string
|
||||||
|
constructor(serviceUrl: string) {
|
||||||
|
this.serviceUrl = serviceUrl
|
||||||
|
}
|
||||||
|
|
||||||
|
getInfo = async () => {
|
||||||
|
const res = await fetch(`${this.serviceUrl}/getinfo`)
|
||||||
|
const json = await res.json() as { options: {}, uris: string[] }
|
||||||
|
}
|
||||||
|
|
||||||
|
createOrder = async (req: { public_key: string }) => {
|
||||||
|
const res = await fetch(`${this.serviceUrl}/create_order`, {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(req),
|
||||||
|
headers: { "Content-Type": "application/json" }
|
||||||
|
})
|
||||||
|
const json = await res.json() as {}
|
||||||
|
return json
|
||||||
|
}
|
||||||
|
|
||||||
|
getOrder = async (orderId: string) => {
|
||||||
|
const res = await fetch(`${this.serviceUrl}/get_order&order_id=${orderId}`)
|
||||||
|
const json = await res.json() as {}
|
||||||
|
return json
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -9,6 +9,8 @@ export type LndSettings = {
|
||||||
feeRateLimit: number
|
feeRateLimit: number
|
||||||
feeFixedLimit: number
|
feeFixedLimit: number
|
||||||
mockLnd: boolean
|
mockLnd: boolean
|
||||||
|
liquidityProviderPub: string
|
||||||
|
useOnlyLiquidityProvider: boolean
|
||||||
|
|
||||||
otherNode?: NodeSettings
|
otherNode?: NodeSettings
|
||||||
thirdNode?: NodeSettings
|
thirdNode?: NodeSettings
|
||||||
|
|
|
||||||
|
|
@ -5,8 +5,9 @@ import { MainSettings } from './settings.js'
|
||||||
import PaymentManager from './paymentManager.js'
|
import PaymentManager from './paymentManager.js'
|
||||||
import { InboundOptionals, defaultInvoiceExpiry } from '../storage/paymentStorage.js'
|
import { InboundOptionals, defaultInvoiceExpiry } from '../storage/paymentStorage.js'
|
||||||
import { ApplicationUser } from '../storage/entity/ApplicationUser.js'
|
import { ApplicationUser } from '../storage/entity/ApplicationUser.js'
|
||||||
import { getLogger } from '../helpers/logger.js'
|
import { PubLogger, getLogger } from '../helpers/logger.js'
|
||||||
import crypto from 'crypto'
|
import crypto from 'crypto'
|
||||||
|
import { Application } from '../storage/entity/Application.js'
|
||||||
|
|
||||||
const TOKEN_EXPIRY_TIME = 2 * 60 * 1000 // 2 minutes, in milliseconds
|
const TOKEN_EXPIRY_TIME = 2 * 60 * 1000 // 2 minutes, in milliseconds
|
||||||
|
|
||||||
|
|
@ -19,11 +20,18 @@ export default class {
|
||||||
settings: MainSettings
|
settings: MainSettings
|
||||||
paymentManager: PaymentManager
|
paymentManager: PaymentManager
|
||||||
nPubLinkingTokens = new Map<string, NsecLinkingData>();
|
nPubLinkingTokens = new Map<string, NsecLinkingData>();
|
||||||
linkingTokenInterval: NodeJS.Timeout
|
linkingTokenInterval: NodeJS.Timeout | null = null
|
||||||
|
serviceBeaconInterval: NodeJS.Timeout | null = null
|
||||||
|
log: PubLogger
|
||||||
constructor(storage: Storage, settings: MainSettings, paymentManager: PaymentManager) {
|
constructor(storage: Storage, settings: MainSettings, paymentManager: PaymentManager) {
|
||||||
|
this.log = getLogger({ component: "ApplicationManager" })
|
||||||
this.storage = storage
|
this.storage = storage
|
||||||
this.settings = settings
|
this.settings = settings
|
||||||
this.paymentManager = paymentManager
|
this.paymentManager = paymentManager
|
||||||
|
this.StartLinkingTokenInterval()
|
||||||
|
}
|
||||||
|
|
||||||
|
StartLinkingTokenInterval() {
|
||||||
this.linkingTokenInterval = setInterval(() => {
|
this.linkingTokenInterval = setInterval(() => {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
for (let [token, data] of this.nPubLinkingTokens) {
|
for (let [token, data] of this.nPubLinkingTokens) {
|
||||||
|
|
@ -36,9 +44,28 @@ export default class {
|
||||||
}
|
}
|
||||||
}, 60 * 1000); // 1 minute
|
}, 60 * 1000); // 1 minute
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async StartAppsServiceBeacon(publishBeacon: (app: Application) => void) {
|
||||||
|
this.serviceBeaconInterval = setInterval(async () => {
|
||||||
|
try {
|
||||||
|
const apps = await this.storage.applicationStorage.GetApplications()
|
||||||
|
apps.forEach(app => {
|
||||||
|
publishBeacon(app)
|
||||||
|
})
|
||||||
|
} catch (e) {
|
||||||
|
this.log("error in beacon", (e as any).message)
|
||||||
|
}
|
||||||
|
}, 60 * 1000)
|
||||||
|
}
|
||||||
|
|
||||||
Stop() {
|
Stop() {
|
||||||
|
if (this.linkingTokenInterval) {
|
||||||
clearInterval(this.linkingTokenInterval)
|
clearInterval(this.linkingTokenInterval)
|
||||||
}
|
}
|
||||||
|
if (this.serviceBeaconInterval) {
|
||||||
|
clearInterval(this.serviceBeaconInterval)
|
||||||
|
}
|
||||||
|
}
|
||||||
SignAppToken(appId: string): string {
|
SignAppToken(appId: string): string {
|
||||||
return jwt.sign({ appId }, this.settings.jwtSecret);
|
return jwt.sign({ appId }, this.settings.jwtSecret);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ import PaymentManager, { PendingTx } from './paymentManager.js'
|
||||||
import { MainSettings } from './settings.js'
|
import { MainSettings } from './settings.js'
|
||||||
import LND from "../lnd/lnd.js"
|
import LND from "../lnd/lnd.js"
|
||||||
import { AddressPaidCb, HtlcCb, InvoicePaidCb, NewBlockCb } from "../lnd/settings.js"
|
import { AddressPaidCb, HtlcCb, InvoicePaidCb, NewBlockCb } from "../lnd/settings.js"
|
||||||
import { getLogger, PubLogger } from "../helpers/logger.js"
|
import { ERROR, getLogger, PubLogger } from "../helpers/logger.js"
|
||||||
import AppUserManager from "./appUserManager.js"
|
import AppUserManager from "./appUserManager.js"
|
||||||
import { Application } from '../storage/entity/Application.js'
|
import { Application } from '../storage/entity/Application.js'
|
||||||
import { UserReceivingInvoice } from '../storage/entity/UserReceivingInvoice.js'
|
import { UserReceivingInvoice } from '../storage/entity/UserReceivingInvoice.js'
|
||||||
|
|
@ -15,6 +15,7 @@ import { UnsignedEvent } from '../nostr/tools/event.js'
|
||||||
import { NostrSend } from '../nostr/handler.js'
|
import { NostrSend } from '../nostr/handler.js'
|
||||||
import MetricsManager from '../metrics/index.js'
|
import MetricsManager from '../metrics/index.js'
|
||||||
import { LoggedEvent } from '../storage/eventsLog.js'
|
import { LoggedEvent } from '../storage/eventsLog.js'
|
||||||
|
import { LiquidityProvider } from "../lnd/liquidityProvider.js"
|
||||||
|
|
||||||
type UserOperationsSub = {
|
type UserOperationsSub = {
|
||||||
id: string
|
id: string
|
||||||
|
|
@ -23,7 +24,7 @@ type UserOperationsSub = {
|
||||||
newIncomingTx: (operation: Types.UserOperation) => void
|
newIncomingTx: (operation: Types.UserOperation) => void
|
||||||
newOutgoingTx: (operation: Types.UserOperation) => void
|
newOutgoingTx: (operation: Types.UserOperation) => void
|
||||||
}
|
}
|
||||||
|
const appTag = "Lightning.Pub"
|
||||||
export default class {
|
export default class {
|
||||||
storage: Storage
|
storage: Storage
|
||||||
lnd: LND
|
lnd: LND
|
||||||
|
|
@ -35,13 +36,13 @@ export default class {
|
||||||
paymentManager: PaymentManager
|
paymentManager: PaymentManager
|
||||||
paymentSubs: Record<string, ((op: Types.UserOperation) => void) | null> = {}
|
paymentSubs: Record<string, ((op: Types.UserOperation) => void) | null> = {}
|
||||||
metricsManager: MetricsManager
|
metricsManager: MetricsManager
|
||||||
|
liquidProvider: LiquidityProvider
|
||||||
nostrSend: NostrSend = () => { getLogger({})("nostr send not initialized yet") }
|
nostrSend: NostrSend = () => { getLogger({})("nostr send not initialized yet") }
|
||||||
|
|
||||||
constructor(settings: MainSettings, storage: Storage) {
|
constructor(settings: MainSettings, storage: Storage) {
|
||||||
this.settings = settings
|
this.settings = settings
|
||||||
this.storage = storage
|
this.storage = storage
|
||||||
|
this.liquidProvider = new LiquidityProvider(settings.lndSettings.liquidityProviderPub, this.invoicePaidCb)
|
||||||
this.lnd = new LND(settings.lndSettings, this.addressPaidCb, this.invoicePaidCb, this.newBlockCb, this.htlcCb)
|
this.lnd = new LND(settings.lndSettings, this.liquidProvider, this.addressPaidCb, this.invoicePaidCb, this.newBlockCb, this.htlcCb)
|
||||||
this.metricsManager = new MetricsManager(this.storage, this.lnd)
|
this.metricsManager = new MetricsManager(this.storage, this.lnd)
|
||||||
|
|
||||||
this.paymentManager = new PaymentManager(this.storage, this.lnd, this.settings, this.addressPaidCb, this.invoicePaidCb)
|
this.paymentManager = new PaymentManager(this.storage, this.lnd, this.settings, this.addressPaidCb, this.invoicePaidCb)
|
||||||
|
|
@ -56,8 +57,15 @@ export default class {
|
||||||
this.paymentManager.Stop()
|
this.paymentManager.Stop()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
StartBeacons() {
|
||||||
|
this.applicationManager.StartAppsServiceBeacon(app => {
|
||||||
|
this.UpdateBeacon(app, { type: 'service', name: app.name })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
attachNostrSend(f: NostrSend) {
|
attachNostrSend(f: NostrSend) {
|
||||||
this.nostrSend = f
|
this.nostrSend = f
|
||||||
|
this.liquidProvider.attachNostrSend(f)
|
||||||
}
|
}
|
||||||
|
|
||||||
htlcCb: HtlcCb = (e) => {
|
htlcCb: HtlcCb = (e) => {
|
||||||
|
|
@ -77,7 +85,7 @@ export default class {
|
||||||
await this.metricsManager.NewBlockCb(height, balanceEvents)
|
await this.metricsManager.NewBlockCb(height, balanceEvents)
|
||||||
confirmed = await this.paymentManager.CheckNewlyConfirmedTxs(height)
|
confirmed = await this.paymentManager.CheckNewlyConfirmedTxs(height)
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
log("failed to check transactions after new block", err.message || err)
|
log(ERROR, "failed to check transactions after new block", err.message || err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
await Promise.all(confirmed.map(async c => {
|
await Promise.all(confirmed.map(async c => {
|
||||||
|
|
@ -91,7 +99,7 @@ export default class {
|
||||||
this.storage.StartTransaction(async tx => {
|
this.storage.StartTransaction(async tx => {
|
||||||
const { user_address: userAddress, paid_amount: amount, service_fee: serviceFee, serial_id: serialId, tx_hash } = c.tx
|
const { user_address: userAddress, paid_amount: amount, service_fee: serviceFee, serial_id: serialId, tx_hash } = c.tx
|
||||||
if (!userAddress.linkedApplication) {
|
if (!userAddress.linkedApplication) {
|
||||||
log("ERROR", "an address was paid, that has no linked application")
|
log(ERROR, "an address was paid, that has no linked application")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const updateResult = await this.storage.paymentStorage.UpdateAddressReceivingTransaction(serialId, { confs: c.confs }, tx)
|
const updateResult = await this.storage.paymentStorage.UpdateAddressReceivingTransaction(serialId, { confs: c.confs }, tx)
|
||||||
|
|
@ -108,7 +116,6 @@ export default class {
|
||||||
const op = { amount, paidAtUnix: Date.now() / 1000, inbound: true, type: Types.UserOperationType.INCOMING_TX, identifier: userAddress.address, operationId, network_fee: 0, service_fee: serviceFee, confirmed: true, tx_hash: c.tx.tx_hash, internal: c.tx.internal }
|
const op = { amount, paidAtUnix: Date.now() / 1000, inbound: true, type: Types.UserOperationType.INCOMING_TX, identifier: userAddress.address, operationId, network_fee: 0, service_fee: serviceFee, confirmed: true, tx_hash: c.tx.tx_hash, internal: c.tx.internal }
|
||||||
this.sendOperationToNostr(userAddress.linkedApplication!, userAddress.user.user_id, op)
|
this.sendOperationToNostr(userAddress.linkedApplication!, userAddress.user.user_id, op)
|
||||||
})
|
})
|
||||||
|
|
||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
@ -120,7 +127,7 @@ export default class {
|
||||||
if (!userAddress) { return }
|
if (!userAddress) { return }
|
||||||
let log = getLogger({})
|
let log = getLogger({})
|
||||||
if (!userAddress.linkedApplication) {
|
if (!userAddress.linkedApplication) {
|
||||||
log("ERROR", "an address was paid, that has no linked application")
|
log(ERROR, "an address was paid, that has no linked application")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
log = getLogger({ appName: userAddress.linkedApplication.name })
|
log = getLogger({ appName: userAddress.linkedApplication.name })
|
||||||
|
|
@ -145,7 +152,7 @@ export default class {
|
||||||
const op = { amount, paidAtUnix: Date.now() / 1000, inbound: true, type: Types.UserOperationType.INCOMING_TX, identifier: userAddress.address, operationId, network_fee: 0, service_fee: fee, confirmed: internal, tx_hash: txOutput.hash, internal: false }
|
const op = { amount, paidAtUnix: Date.now() / 1000, inbound: true, type: Types.UserOperationType.INCOMING_TX, identifier: userAddress.address, operationId, network_fee: 0, service_fee: fee, confirmed: internal, tx_hash: txOutput.hash, internal: false }
|
||||||
this.sendOperationToNostr(userAddress.linkedApplication, userAddress.user.user_id, op)
|
this.sendOperationToNostr(userAddress.linkedApplication, userAddress.user.user_id, op)
|
||||||
} catch {
|
} catch {
|
||||||
|
log(ERROR, "cannot process address paid transaction, already registered")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -158,7 +165,7 @@ export default class {
|
||||||
if (userInvoice.paid_at_unix > 0 && internal) { log("cannot pay internally, invoice already paid"); return }
|
if (userInvoice.paid_at_unix > 0 && internal) { log("cannot pay internally, invoice already paid"); return }
|
||||||
if (userInvoice.paid_at_unix > 0 && !internal && userInvoice.paidByLnd) { log("invoice already paid by lnd"); return }
|
if (userInvoice.paid_at_unix > 0 && !internal && userInvoice.paidByLnd) { log("invoice already paid by lnd"); return }
|
||||||
if (!userInvoice.linkedApplication) {
|
if (!userInvoice.linkedApplication) {
|
||||||
log("ERROR", "an invoice was paid, that has no linked application")
|
log(ERROR, "an invoice was paid, that has no linked application")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
log = getLogger({ appName: userInvoice.linkedApplication.name })
|
log = getLogger({ appName: userInvoice.linkedApplication.name })
|
||||||
|
|
@ -181,7 +188,7 @@ export default class {
|
||||||
this.createZapReceipt(log, userInvoice)
|
this.createZapReceipt(log, userInvoice)
|
||||||
log("paid invoice processed successfully")
|
log("paid invoice processed successfully")
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
log("ERROR", "cannot process paid invoice", err.message || "")
|
log(ERROR, "cannot process paid invoice", err.message || "")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -193,7 +200,7 @@ export default class {
|
||||||
try {
|
try {
|
||||||
await fetch(url + "&ok=true")
|
await fetch(url + "&ok=true")
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
log("error sending paid callback for invoice", err.message || "")
|
log(ERROR, "error sending paid callback for invoice", err.message || "")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -204,13 +211,29 @@ export default class {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const message: Types.LiveUserOperation & { requestId: string, status: 'OK' } = { operation: op, requestId: "GetLiveUserOperations", status: 'OK' }
|
const message: Types.LiveUserOperation & { requestId: string, status: 'OK' } = { operation: op, requestId: "GetLiveUserOperations", status: 'OK' }
|
||||||
this.nostrSend(app.app_id, { type: 'content', content: JSON.stringify(message), pub: user.nostr_public_key })
|
this.nostrSend({ type: 'app', appId: app.app_id }, { type: 'content', content: JSON.stringify(message), pub: user.nostr_public_key })
|
||||||
|
}
|
||||||
|
|
||||||
|
async UpdateBeacon(app: Application, content: { type: 'service', name: string }) {
|
||||||
|
if (!app.nostr_public_key) {
|
||||||
|
getLogger({ appName: app.name })("cannot update beacon, public key not set")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const tags = [["d", appTag]]
|
||||||
|
const event: UnsignedEvent = {
|
||||||
|
content: JSON.stringify(content),
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: 30078,
|
||||||
|
pubkey: app.nostr_public_key,
|
||||||
|
tags,
|
||||||
|
}
|
||||||
|
this.nostrSend({ type: 'app', appId: app.app_id }, { type: 'event', event })
|
||||||
}
|
}
|
||||||
|
|
||||||
async createZapReceipt(log: PubLogger, invoice: UserReceivingInvoice) {
|
async createZapReceipt(log: PubLogger, invoice: UserReceivingInvoice) {
|
||||||
const zapInfo = invoice.zap_info
|
const zapInfo = invoice.zap_info
|
||||||
if (!zapInfo || !invoice.linkedApplication || !invoice.linkedApplication.nostr_public_key) {
|
if (!zapInfo || !invoice.linkedApplication || !invoice.linkedApplication.nostr_public_key) {
|
||||||
log("no zap info linked to payment")
|
log(ERROR, "no zap info linked to payment")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const tags = [["p", zapInfo.pub], ["bolt11", invoice.invoice], ["description", zapInfo.description]]
|
const tags = [["p", zapInfo.pub], ["bolt11", invoice.invoice], ["description", zapInfo.description]]
|
||||||
|
|
@ -225,6 +248,6 @@ export default class {
|
||||||
tags,
|
tags,
|
||||||
}
|
}
|
||||||
log({ unsigned: event })
|
log({ unsigned: event })
|
||||||
this.nostrSend(invoice.linkedApplication.app_id, { type: 'event', event })
|
this.nostrSend({ type: 'app', appId: invoice.linkedApplication.app_id }, { type: 'event', event })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import { PubLogger, getLogger } from "../helpers/logger.js"
|
import { PubLogger, getLogger } from "../helpers/logger.js"
|
||||||
|
import { LiquidityProvider } from "../lnd/liquidityProvider.js"
|
||||||
import Storage from "../storage/index.js"
|
import Storage from "../storage/index.js"
|
||||||
import { TypeOrmMigrationRunner } from "../storage/migrations/runner.js"
|
import { TypeOrmMigrationRunner } from "../storage/migrations/runner.js"
|
||||||
import Main from "./index.js"
|
import Main from "./index.js"
|
||||||
|
|
@ -16,6 +17,7 @@ export const initMainHandler = async (log: PubLogger, mainSettings: MainSettings
|
||||||
if (manualMigration) {
|
if (manualMigration) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const mainHandler = new Main(mainSettings, storageManager)
|
const mainHandler = new Main(mainSettings, storageManager)
|
||||||
await mainHandler.lnd.Warmup()
|
await mainHandler.lnd.Warmup()
|
||||||
if (!mainSettings.skipSanityCheck) {
|
if (!mainSettings.skipSanityCheck) {
|
||||||
|
|
@ -38,11 +40,21 @@ export const initMainHandler = async (log: PubLogger, mainSettings: MainSettings
|
||||||
return { privateKey: app.nostr_private_key, publicKey: app.nostr_public_key, appId: app.app_id, name: app.name }
|
return { privateKey: app.nostr_private_key, publicKey: app.nostr_public_key, appId: app.app_id, name: app.name }
|
||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
|
const liquidityProviderApp = apps.find(app => app.name === 'wallet' || app.name === 'wallet-test')
|
||||||
|
if (!liquidityProviderApp) {
|
||||||
|
throw new Error("wallet app not initialized correctly")
|
||||||
|
}
|
||||||
|
const liquidityProviderInfo = {
|
||||||
|
privateKey: liquidityProviderApp.privateKey,
|
||||||
|
publicKey: liquidityProviderApp.publicKey,
|
||||||
|
name: "liquidity_provider", clientId: `client_${liquidityProviderApp.appId}`
|
||||||
|
}
|
||||||
|
mainHandler.liquidProvider.setNostrInfo({ clientId: liquidityProviderInfo.clientId, myPub: liquidityProviderInfo.publicKey })
|
||||||
const stop = await processArgs(mainHandler)
|
const stop = await processArgs(mainHandler)
|
||||||
if (stop) {
|
if (stop) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
return { mainHandler, apps }
|
return { mainHandler, apps, liquidityProviderInfo, liquidityProviderApp }
|
||||||
}
|
}
|
||||||
|
|
||||||
const processArgs = async (mainHandler: Main) => {
|
const processArgs = async (mainHandler: Main) => {
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,7 @@ import { Event, verifiedSymbol, verifySignature } from '../nostr/tools/event.js'
|
||||||
import { AddressReceivingTransaction } from '../storage/entity/AddressReceivingTransaction.js'
|
import { AddressReceivingTransaction } from '../storage/entity/AddressReceivingTransaction.js'
|
||||||
import { UserTransactionPayment } from '../storage/entity/UserTransactionPayment.js'
|
import { UserTransactionPayment } from '../storage/entity/UserTransactionPayment.js'
|
||||||
import { Watchdog } from './watchdog.js'
|
import { Watchdog } from './watchdog.js'
|
||||||
|
import { LiquidityProvider } from '../lnd/liquidityProvider.js'
|
||||||
interface UserOperationInfo {
|
interface UserOperationInfo {
|
||||||
serial_id: number
|
serial_id: number
|
||||||
paid_amount: number
|
paid_amount: number
|
||||||
|
|
@ -39,13 +40,12 @@ const defaultLnurlPayMetadata = `[["text/plain", "lnurl pay to Lightning.pub"]]`
|
||||||
const confInOne = 1000 * 1000
|
const confInOne = 1000 * 1000
|
||||||
const confInTwo = 100 * 1000 * 1000
|
const confInTwo = 100 * 1000 * 1000
|
||||||
export default class {
|
export default class {
|
||||||
|
|
||||||
storage: Storage
|
storage: Storage
|
||||||
settings: MainSettings
|
settings: MainSettings
|
||||||
lnd: LND
|
lnd: LND
|
||||||
addressPaidCb: AddressPaidCb
|
addressPaidCb: AddressPaidCb
|
||||||
invoicePaidCb: InvoicePaidCb
|
invoicePaidCb: InvoicePaidCb
|
||||||
log = getLogger({ appName: "PaymentManager" })
|
log = getLogger({ component: "PaymentManager" })
|
||||||
watchDog: Watchdog
|
watchDog: Watchdog
|
||||||
constructor(storage: Storage, lnd: LND, settings: MainSettings, addressPaidCb: AddressPaidCb, invoicePaidCb: InvoicePaidCb) {
|
constructor(storage: Storage, lnd: LND, settings: MainSettings, addressPaidCb: AddressPaidCb, invoicePaidCb: InvoicePaidCb) {
|
||||||
this.storage = storage
|
this.storage = storage
|
||||||
|
|
@ -297,7 +297,7 @@ export default class {
|
||||||
}
|
}
|
||||||
|
|
||||||
async GetLnurlWithdrawLink(ctx: Types.UserContext): Promise<Types.LnurlLinkResponse> {
|
async GetLnurlWithdrawLink(ctx: Types.UserContext): Promise<Types.LnurlLinkResponse> {
|
||||||
if(this.isDefaultServiceUrl()) {
|
if (this.isDefaultServiceUrl()) {
|
||||||
throw new Error("Lnurl not enabled. Make sure to set SERVICE_URL env variable")
|
throw new Error("Lnurl not enabled. Make sure to set SERVICE_URL env variable")
|
||||||
}
|
}
|
||||||
const app = await this.storage.applicationStorage.GetApplication(ctx.app_id)
|
const app = await this.storage.applicationStorage.GetApplication(ctx.app_id)
|
||||||
|
|
@ -345,7 +345,7 @@ export default class {
|
||||||
}
|
}
|
||||||
|
|
||||||
async GetLnurlPayLink(ctx: Types.UserContext): Promise<Types.LnurlLinkResponse> {
|
async GetLnurlPayLink(ctx: Types.UserContext): Promise<Types.LnurlLinkResponse> {
|
||||||
if(this.isDefaultServiceUrl()) {
|
if (this.isDefaultServiceUrl()) {
|
||||||
throw new Error("Lnurl not enabled. Make sure to set SERVICE_URL env variable")
|
throw new Error("Lnurl not enabled. Make sure to set SERVICE_URL env variable")
|
||||||
}
|
}
|
||||||
getLogger({})("getting lnurl pay link")
|
getLogger({})("getting lnurl pay link")
|
||||||
|
|
@ -360,7 +360,7 @@ export default class {
|
||||||
}
|
}
|
||||||
|
|
||||||
async GetLnurlPayInfoFromUser(userId: string, linkedApplication: Application, baseUrl?: string): Promise<Types.LnurlPayInfoResponse> {
|
async GetLnurlPayInfoFromUser(userId: string, linkedApplication: Application, baseUrl?: string): Promise<Types.LnurlPayInfoResponse> {
|
||||||
if(this.isDefaultServiceUrl()) {
|
if (this.isDefaultServiceUrl()) {
|
||||||
throw new Error("Lnurl not enabled. Make sure to set SERVICE_URL env variable")
|
throw new Error("Lnurl not enabled. Make sure to set SERVICE_URL env variable")
|
||||||
}
|
}
|
||||||
const payK1 = await this.storage.paymentStorage.AddUserEphemeralKey(userId, 'pay', linkedApplication)
|
const payK1 = await this.storage.paymentStorage.AddUserEphemeralKey(userId, 'pay', linkedApplication)
|
||||||
|
|
@ -378,7 +378,7 @@ export default class {
|
||||||
}
|
}
|
||||||
|
|
||||||
async GetLnurlPayInfo(payInfoK1: string): Promise<Types.LnurlPayInfoResponse> {
|
async GetLnurlPayInfo(payInfoK1: string): Promise<Types.LnurlPayInfoResponse> {
|
||||||
if(this.isDefaultServiceUrl()) {
|
if (this.isDefaultServiceUrl()) {
|
||||||
throw new Error("Lnurl not enabled. Make sure to set SERVICE_URL env variable")
|
throw new Error("Lnurl not enabled. Make sure to set SERVICE_URL env variable")
|
||||||
}
|
}
|
||||||
const key = await this.storage.paymentStorage.UseUserEphemeralKey(payInfoK1, 'pay', true)
|
const key = await this.storage.paymentStorage.UseUserEphemeralKey(payInfoK1, 'pay', true)
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,7 @@ export default class SanityChecker {
|
||||||
incrementSources: Record<string, boolean> = {}
|
incrementSources: Record<string, boolean> = {}
|
||||||
decrementSources: Record<string, boolean> = {}
|
decrementSources: Record<string, boolean> = {}
|
||||||
decrementEvents: Record<string, { userId: string, refund: number, failure: boolean }> = {}
|
decrementEvents: Record<string, { userId: string, refund: number, failure: boolean }> = {}
|
||||||
log = getLogger({ appName: "SanityChecker" })
|
log = getLogger({ component: "SanityChecker" })
|
||||||
users: Record<string, { ts: number, updatedBalance: number }> = {}
|
users: Record<string, { ts: number, updatedBalance: number }> = {}
|
||||||
constructor(storage: Storage, lnd: LND) {
|
constructor(storage: Storage, lnd: LND) {
|
||||||
this.storage = storage
|
this.storage = storage
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,10 @@ import { LoadStorageSettingsFromEnv, StorageSettings } from '../storage/index.js
|
||||||
import { LndSettings, NodeSettings } from '../lnd/settings.js'
|
import { LndSettings, NodeSettings } from '../lnd/settings.js'
|
||||||
import { LoadWatchdogSettingsFromEnv, WatchdogSettings } from './watchdog.js'
|
import { LoadWatchdogSettingsFromEnv, WatchdogSettings } from './watchdog.js'
|
||||||
import { LoadLndSettingsFromEnv } from '../lnd/index.js'
|
import { LoadLndSettingsFromEnv } from '../lnd/index.js'
|
||||||
import { EnvMustBeInteger, EnvMustBeNonEmptyString } from '../helpers/envParser.js'
|
import { EnvCanBeInteger, EnvMustBeInteger, EnvMustBeNonEmptyString } from '../helpers/envParser.js'
|
||||||
|
import { getLogger } from '../helpers/logger.js'
|
||||||
|
import fs from 'fs'
|
||||||
|
import crypto from 'crypto';
|
||||||
export type MainSettings = {
|
export type MainSettings = {
|
||||||
storageSettings: StorageSettings,
|
storageSettings: StorageSettings,
|
||||||
lndSettings: LndSettings,
|
lndSettings: LndSettings,
|
||||||
|
|
@ -33,20 +36,20 @@ export const LoadMainSettingsFromEnv = (): MainSettings => {
|
||||||
watchDogSettings: LoadWatchdogSettingsFromEnv(),
|
watchDogSettings: LoadWatchdogSettingsFromEnv(),
|
||||||
lndSettings: LoadLndSettingsFromEnv(),
|
lndSettings: LoadLndSettingsFromEnv(),
|
||||||
storageSettings: LoadStorageSettingsFromEnv(),
|
storageSettings: LoadStorageSettingsFromEnv(),
|
||||||
jwtSecret: EnvMustBeNonEmptyString("JWT_SECRET"),
|
jwtSecret: loadJwtSecret(),
|
||||||
incomingTxFee: EnvMustBeInteger("INCOMING_CHAIN_FEE_ROOT_BPS") / 10000,
|
incomingTxFee: EnvCanBeInteger("INCOMING_CHAIN_FEE_ROOT_BPS", 0) / 10000,
|
||||||
outgoingTxFee: EnvMustBeInteger("OUTGOING_CHAIN_FEE_ROOT_BPS") / 10000,
|
outgoingTxFee: EnvCanBeInteger("OUTGOING_CHAIN_FEE_ROOT_BPS", 60) / 10000,
|
||||||
incomingAppInvoiceFee: EnvMustBeInteger("INCOMING_INVOICE_FEE_ROOT_BPS") / 10000,
|
incomingAppInvoiceFee: EnvCanBeInteger("INCOMING_INVOICE_FEE_ROOT_BPS", 0) / 10000,
|
||||||
outgoingAppInvoiceFee: EnvMustBeInteger("OUTGOING_INVOICE_FEE_ROOT_BPS") / 10000,
|
outgoingAppInvoiceFee: EnvCanBeInteger("OUTGOING_INVOICE_FEE_ROOT_BPS", 60) / 10000,
|
||||||
incomingAppUserInvoiceFee: EnvMustBeInteger("INCOMING_INVOICE_FEE_USER_BPS") / 10000,
|
incomingAppUserInvoiceFee: EnvCanBeInteger("INCOMING_INVOICE_FEE_USER_BPS", 0) / 10000,
|
||||||
outgoingAppUserInvoiceFee: EnvMustBeInteger("OUTGOING_INVOICE_FEE_USER_BPS") / 10000,
|
outgoingAppUserInvoiceFee: EnvCanBeInteger("OUTGOING_INVOICE_FEE_USER_BPS", 0) / 10000,
|
||||||
userToUserFee: EnvMustBeInteger("TX_FEE_INTERNAL_USER_BPS") / 10000,
|
userToUserFee: EnvCanBeInteger("TX_FEE_INTERNAL_USER_BPS", 0) / 10000,
|
||||||
appToUserFee: EnvMustBeInteger("TX_FEE_INTERNAL_ROOT_BPS") / 10000,
|
appToUserFee: EnvCanBeInteger("TX_FEE_INTERNAL_ROOT_BPS", 0) / 10000,
|
||||||
serviceUrl: process.env.SERVICE_URL || `http://localhost:${EnvMustBeInteger("PORT")}`,
|
serviceUrl: process.env.SERVICE_URL || `http://localhost:${EnvCanBeInteger("PORT", 1776)}`,
|
||||||
servicePort: EnvMustBeInteger("PORT"),
|
servicePort: EnvCanBeInteger("PORT", 1776),
|
||||||
recordPerformance: process.env.RECORD_PERFORMANCE === 'true' || false,
|
recordPerformance: process.env.RECORD_PERFORMANCE === 'true' || false,
|
||||||
skipSanityCheck: process.env.SKIP_SANITY_CHECK === 'true' || false,
|
skipSanityCheck: process.env.SKIP_SANITY_CHECK === 'true' || false,
|
||||||
disableExternalPayments: process.env.DISABLE_EXTERNAL_PAYMENTS === 'true' || false
|
disableExternalPayments: process.env.DISABLE_EXTERNAL_PAYMENTS === 'true' || false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -72,13 +75,32 @@ export const LoadTestSettingsFromEnv = (): TestSettings => {
|
||||||
lndAddr: EnvMustBeNonEmptyString("LND_FOURTH_ADDR"),
|
lndAddr: EnvMustBeNonEmptyString("LND_FOURTH_ADDR"),
|
||||||
lndCertPath: EnvMustBeNonEmptyString("LND_FOURTH_CERT_PATH"),
|
lndCertPath: EnvMustBeNonEmptyString("LND_FOURTH_CERT_PATH"),
|
||||||
lndMacaroonPath: EnvMustBeNonEmptyString("LND_FOURTH_MACAROON_PATH")
|
lndMacaroonPath: EnvMustBeNonEmptyString("LND_FOURTH_MACAROON_PATH")
|
||||||
}
|
},
|
||||||
|
liquidityProviderPub: ""
|
||||||
},
|
},
|
||||||
skipSanityCheck: true,
|
skipSanityCheck: true,
|
||||||
bitcoinCoreSettings: {
|
bitcoinCoreSettings: {
|
||||||
port: EnvMustBeInteger("BITCOIN_CORE_PORT"),
|
port: EnvMustBeInteger("BITCOIN_CORE_PORT"),
|
||||||
user: EnvMustBeNonEmptyString("BITCOIN_CORE_USER"),
|
user: EnvMustBeNonEmptyString("BITCOIN_CORE_USER"),
|
||||||
pass: EnvMustBeNonEmptyString("BITCOIN_CORE_PASS")
|
pass: EnvMustBeNonEmptyString("BITCOIN_CORE_PASS")
|
||||||
}
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const loadJwtSecret = (): string => {
|
||||||
|
const secret = process.env["JWT_SECRET"]
|
||||||
|
const log = getLogger({})
|
||||||
|
if (secret) {
|
||||||
|
return secret
|
||||||
|
}
|
||||||
|
log("JWT_SECRET not set in env, checking .jwt_secret file")
|
||||||
|
try {
|
||||||
|
const fileContent = fs.readFileSync(".jwt_secret", "utf-8")
|
||||||
|
return fileContent.trim()
|
||||||
|
} catch (e) {
|
||||||
|
log(".jwt_secret file not found, generating random secret")
|
||||||
|
const secret = crypto.randomBytes(32).toString('hex')
|
||||||
|
fs.writeFileSync(".jwt_secret", secret)
|
||||||
|
return secret
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -23,14 +23,14 @@ export class Watchdog {
|
||||||
settings: WatchdogSettings;
|
settings: WatchdogSettings;
|
||||||
storage: Storage;
|
storage: Storage;
|
||||||
latestCheckStart = 0
|
latestCheckStart = 0
|
||||||
log = getLogger({ appName: "watchdog" })
|
log = getLogger({ component: "watchdog" })
|
||||||
ready = false
|
ready = false
|
||||||
interval: NodeJS.Timer;
|
interval: NodeJS.Timer;
|
||||||
constructor(settings: WatchdogSettings, lnd: LND, storage: Storage) {
|
constructor(settings: WatchdogSettings, lnd: LND, storage: Storage) {
|
||||||
this.lnd = lnd;
|
this.lnd = lnd;
|
||||||
this.settings = settings;
|
this.settings = settings;
|
||||||
this.storage = storage;
|
this.storage = storage;
|
||||||
this.queue = new FunctionQueue("watchdog::queue", () => this.StartCheck())
|
this.queue = new FunctionQueue("watchdog_queue", () => this.StartCheck())
|
||||||
}
|
}
|
||||||
|
|
||||||
Stop() {
|
Stop() {
|
||||||
|
|
@ -73,11 +73,10 @@ export class Watchdog {
|
||||||
const walletBalance = await this.lnd.GetWalletBalance()
|
const walletBalance = await this.lnd.GetWalletBalance()
|
||||||
this.log(Number(walletBalance.confirmedBalance), "sats in chain wallet")
|
this.log(Number(walletBalance.confirmedBalance), "sats in chain wallet")
|
||||||
const channelsBalance = await this.lnd.GetChannelBalance()
|
const channelsBalance = await this.lnd.GetChannelBalance()
|
||||||
getLogger({ appName: "debugLndBalancev3" })({ w: walletBalance, c: channelsBalance, u: usersTotal, f: this.accumulatedHtlcFees })
|
getLogger({ component: "debugLndBalancev3" })({ w: walletBalance, c: channelsBalance, u: usersTotal, f: this.accumulatedHtlcFees })
|
||||||
|
const totalLightningBalanceMsats = (channelsBalance.localBalance?.msat || 0n) + (channelsBalance.unsettledLocalBalance?.msat || 0n)
|
||||||
const localChannelsBalance = Number(channelsBalance.localBalance?.sat || 0)
|
const totalLightningBalance = Math.ceil(Number(totalLightningBalanceMsats) / 1000)
|
||||||
const unsettledLocalBalance = Number(channelsBalance.unsettledLocalBalance?.sat || 0)
|
return Number(walletBalance.confirmedBalance) + totalLightningBalance
|
||||||
return Number(walletBalance.confirmedBalance) + localChannelsBalance + unsettledLocalBalance
|
|
||||||
}
|
}
|
||||||
|
|
||||||
checkBalanceUpdate = (deltaLnd: number, deltaUsers: number) => {
|
checkBalanceUpdate = (deltaLnd: number, deltaUsers: number) => {
|
||||||
|
|
|
||||||
|
|
@ -16,9 +16,9 @@ export default class HtlcTracker {
|
||||||
constructor(storage: Storage) {
|
constructor(storage: Storage) {
|
||||||
this.storage = storage
|
this.storage = storage
|
||||||
}
|
}
|
||||||
log = getLogger({ appName: 'htlcTracker' })
|
log = getLogger({ component: 'htlcTracker' })
|
||||||
onHtlcEvent = async (htlc: HtlcEvent) => {
|
onHtlcEvent = async (htlc: HtlcEvent) => {
|
||||||
getLogger({ appName: 'debugHtlcs' })(htlc)
|
getLogger({ component: 'debugHtlcs' })(htlc)
|
||||||
const htlcEvent = htlc.event
|
const htlcEvent = htlc.event
|
||||||
if (htlcEvent.oneofKind === 'subscribedEvent') {
|
if (htlcEvent.oneofKind === 'subscribedEvent') {
|
||||||
this.log("htlc subscribed")
|
this.log("htlc subscribed")
|
||||||
|
|
|
||||||
|
|
@ -1,16 +1,19 @@
|
||||||
//import { SimplePool, Sub, Event, UnsignedEvent, getEventHash, signEvent } from 'nostr-tools'
|
//import { SimplePool, Sub, Event, UnsignedEvent, getEventHash, signEvent } from 'nostr-tools'
|
||||||
import { SimplePool, Sub, Event, UnsignedEvent, getEventHash, finishEvent, relayInit } from './tools/index.js'
|
import { SimplePool, Sub, Event, UnsignedEvent, getEventHash, finishEvent, relayInit } from './tools/index.js'
|
||||||
import { encryptData, decryptData, getSharedSecret, decodePayload, encodePayload } from './nip44.js'
|
import { encryptData, decryptData, getSharedSecret, decodePayload, encodePayload } from './nip44.js'
|
||||||
import { getLogger } from '../helpers/logger.js'
|
import { ERROR, getLogger } from '../helpers/logger.js'
|
||||||
import { encodeNprofile } from '../../custom-nip19.js'
|
import { encodeNprofile } from '../../custom-nip19.js'
|
||||||
const handledEvents: string[] = [] // TODO: - big memory leak here, add TTL
|
const handledEvents: string[] = [] // TODO: - big memory leak here, add TTL
|
||||||
type AppInfo = { appId: string, publicKey: string, privateKey: string, name: string }
|
type AppInfo = { appId: string, publicKey: string, privateKey: string, name: string }
|
||||||
|
type ClientInfo = { clientId: string, publicKey: string, privateKey: string, name: string }
|
||||||
export type SendData = { type: "content", content: string, pub: string } | { type: "event", event: UnsignedEvent }
|
export type SendData = { type: "content", content: string, pub: string } | { type: "event", event: UnsignedEvent }
|
||||||
export type NostrSend = (appId: string, data: SendData, relays?: string[] | undefined) => void
|
export type SendInitiator = { type: 'app', appId: string } | { type: 'client', clientId: string }
|
||||||
|
export type NostrSend = (initiator: SendInitiator, data: SendData, relays?: string[] | undefined) => void
|
||||||
|
|
||||||
export type NostrSettings = {
|
export type NostrSettings = {
|
||||||
apps: AppInfo[]
|
apps: AppInfo[]
|
||||||
relays: string[]
|
relays: string[]
|
||||||
|
clients: ClientInfo[]
|
||||||
}
|
}
|
||||||
export type NostrEvent = {
|
export type NostrEvent = {
|
||||||
id: string
|
id: string
|
||||||
|
|
@ -20,6 +23,7 @@ export type NostrEvent = {
|
||||||
startAtNano: string
|
startAtNano: string
|
||||||
startAtMs: number
|
startAtMs: number
|
||||||
}
|
}
|
||||||
|
|
||||||
type SettingsRequest = {
|
type SettingsRequest = {
|
||||||
type: 'settings'
|
type: 'settings'
|
||||||
settings: NostrSettings
|
settings: NostrSettings
|
||||||
|
|
@ -27,7 +31,7 @@ type SettingsRequest = {
|
||||||
|
|
||||||
type SendRequest = {
|
type SendRequest = {
|
||||||
type: 'send'
|
type: 'send'
|
||||||
appId: string
|
initiator: SendInitiator
|
||||||
data: SendData
|
data: SendData
|
||||||
relays?: string[]
|
relays?: string[]
|
||||||
}
|
}
|
||||||
|
|
@ -53,16 +57,16 @@ process.on("message", (message: ChildProcessRequest) => {
|
||||||
initSubprocessHandler(message.settings)
|
initSubprocessHandler(message.settings)
|
||||||
break
|
break
|
||||||
case 'send':
|
case 'send':
|
||||||
sendToNostr(message.appId, message.data, message.relays)
|
sendToNostr(message.initiator, message.data, message.relays)
|
||||||
break
|
break
|
||||||
default:
|
default:
|
||||||
getLogger({ appName: "nostrMiddleware" })("ERROR", "unknown nostr request", message)
|
getLogger({ component: "nostrMiddleware" })(ERROR, "unknown nostr request", message)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
const initSubprocessHandler = (settings: NostrSettings) => {
|
const initSubprocessHandler = (settings: NostrSettings) => {
|
||||||
if (subProcessHandler) {
|
if (subProcessHandler) {
|
||||||
getLogger({ appName: "nostrMiddleware" })("ERROR", "nostr settings ignored since handler already exists")
|
getLogger({ component: "nostrMiddleware" })(ERROR, "nostr settings ignored since handler already exists")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
subProcessHandler = new Handler(settings, event => {
|
subProcessHandler = new Handler(settings, event => {
|
||||||
|
|
@ -72,12 +76,12 @@ const initSubprocessHandler = (settings: NostrSettings) => {
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
const sendToNostr: NostrSend = (appId, data, relays) => {
|
const sendToNostr: NostrSend = (initiator, data, relays) => {
|
||||||
if (!subProcessHandler) {
|
if (!subProcessHandler) {
|
||||||
getLogger({ appName: "nostrMiddleware" })("ERROR", "nostr was not initialized")
|
getLogger({ component: "nostrMiddleware" })(ERROR, "nostr was not initialized")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
subProcessHandler.Send(appId, data, relays)
|
subProcessHandler.Send(initiator, data, relays)
|
||||||
}
|
}
|
||||||
send({ type: 'ready' })
|
send({ type: 'ready' })
|
||||||
|
|
||||||
|
|
@ -87,7 +91,7 @@ export default class Handler {
|
||||||
subs: Sub[] = []
|
subs: Sub[] = []
|
||||||
apps: Record<string, AppInfo> = {}
|
apps: Record<string, AppInfo> = {}
|
||||||
eventCallback: (event: NostrEvent) => void
|
eventCallback: (event: NostrEvent) => void
|
||||||
log = getLogger({ appName: "nostrMiddleware" })
|
log = getLogger({ component: "nostrMiddleware" })
|
||||||
constructor(settings: NostrSettings, eventCallback: (event: NostrEvent) => void) {
|
constructor(settings: NostrSettings, eventCallback: (event: NostrEvent) => void) {
|
||||||
this.settings = settings
|
this.settings = settings
|
||||||
this.log(
|
this.log(
|
||||||
|
|
@ -147,9 +151,14 @@ export default class Handler {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const app = this.apps[pubTags[1]]
|
const app = this.apps[pubTags[1]]
|
||||||
if (!app) {
|
if (app) {
|
||||||
|
await this.processEvent(e, app)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async processEvent(e: Event<21000>, app: AppInfo) {
|
||||||
const eventId = e.id
|
const eventId = e.id
|
||||||
if (handledEvents.includes(eventId)) {
|
if (handledEvents.includes(eventId)) {
|
||||||
this.log("event already handled")
|
this.log("event already handled")
|
||||||
|
|
@ -161,29 +170,28 @@ export default class Handler {
|
||||||
const decoded = decodePayload(e.content)
|
const decoded = decodePayload(e.content)
|
||||||
const content = await decryptData(decoded, getSharedSecret(app.privateKey, e.pubkey))
|
const content = await decryptData(decoded, getSharedSecret(app.privateKey, e.pubkey))
|
||||||
this.eventCallback({ id: eventId, content, pub: e.pubkey, appId: app.appId, startAtNano, startAtMs })
|
this.eventCallback({ id: eventId, content, pub: e.pubkey, appId: app.appId, startAtNano, startAtMs })
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async Send(appId: string, data: SendData, relays?: string[]) {
|
async Send(initiator: SendInitiator, data: SendData, relays?: string[]) {
|
||||||
const appInfo = this.GetAppKeys({ appId })
|
const keys = this.GetSendKeys(initiator)
|
||||||
let toSign: UnsignedEvent
|
let toSign: UnsignedEvent
|
||||||
if (data.type === 'content') {
|
if (data.type === 'content') {
|
||||||
const decoded = await encryptData(data.content, getSharedSecret(appInfo.privateKey, data.pub))
|
const decoded = await encryptData(data.content, getSharedSecret(keys.privateKey, data.pub))
|
||||||
const content = encodePayload(decoded)
|
const content = encodePayload(decoded)
|
||||||
toSign = {
|
toSign = {
|
||||||
content,
|
content,
|
||||||
created_at: Math.floor(Date.now() / 1000),
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
kind: 21000,
|
kind: 21000,
|
||||||
pubkey: appInfo.publicKey,
|
pubkey: keys.publicKey,
|
||||||
tags: [['p', data.pub]],
|
tags: [['p', data.pub]],
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
toSign = data.event
|
toSign = data.event
|
||||||
}
|
}
|
||||||
|
|
||||||
const signed = finishEvent(toSign, appInfo.privateKey)
|
const signed = finishEvent(toSign, keys.privateKey)
|
||||||
let sent = false
|
let sent = false
|
||||||
const log = getLogger({ appName: appInfo.name })
|
const log = getLogger({ appName: keys.name })
|
||||||
await Promise.all(this.pool.publish(relays || this.settings.relays, signed).map(async p => {
|
await Promise.all(this.pool.publish(relays || this.settings.relays, signed).map(async p => {
|
||||||
try {
|
try {
|
||||||
await p
|
await p
|
||||||
|
|
@ -197,21 +205,22 @@ export default class Handler {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
GetAppKeys(appInfo: Partial<AppInfo>) {
|
GetSendKeys(initiator: SendInitiator) {
|
||||||
let check: (info: AppInfo) => boolean
|
if (initiator.type === 'app') {
|
||||||
if (appInfo.appId) {
|
const { appId } = initiator
|
||||||
check = (info: AppInfo) => info.appId === appInfo.appId
|
const found = this.settings.apps.find((info: AppInfo) => info.appId === appId)
|
||||||
} else if (appInfo.privateKey) {
|
|
||||||
check = (info: AppInfo) => info.privateKey === appInfo.privateKey
|
|
||||||
} else if (appInfo.publicKey) {
|
|
||||||
check = (info: AppInfo) => info.publicKey === appInfo.publicKey
|
|
||||||
} else {
|
|
||||||
throw new Error("app info is empty")
|
|
||||||
}
|
|
||||||
const found = this.settings.apps.find(check)
|
|
||||||
if (!found) {
|
if (!found) {
|
||||||
throw new Error("unkown app")
|
throw new Error("unkown app")
|
||||||
}
|
}
|
||||||
return found
|
return found
|
||||||
|
} else if (initiator.type === 'client') {
|
||||||
|
const { clientId } = initiator
|
||||||
|
const found = this.settings.clients.find((info: ClientInfo) => info.clientId === clientId)
|
||||||
|
if (!found) {
|
||||||
|
throw new Error("unkown client")
|
||||||
|
}
|
||||||
|
return found
|
||||||
|
}
|
||||||
|
throw new Error("unkown initiator type")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1,12 +1,19 @@
|
||||||
import { ChildProcess, fork } from 'child_process'
|
import { ChildProcess, fork } from 'child_process'
|
||||||
import { EnvMustBeNonEmptyString } from "../helpers/envParser.js"
|
import { EnvMustBeNonEmptyString } from "../helpers/envParser.js"
|
||||||
import { NostrSettings, NostrEvent, ChildProcessRequest, ChildProcessResponse, SendData } from "./handler.js"
|
import { NostrSettings, NostrEvent, ChildProcessRequest, ChildProcessResponse, SendData, SendInitiator } from "./handler.js"
|
||||||
type EventCallback = (event: NostrEvent) => void
|
type EventCallback = (event: NostrEvent) => void
|
||||||
|
|
||||||
|
const getEnvOrDefault = (name: string, defaultValue: string): string => {
|
||||||
|
return process.env[name] || defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
export const LoadNosrtSettingsFromEnv = (test = false) => {
|
export const LoadNosrtSettingsFromEnv = (test = false) => {
|
||||||
|
const relaysEnv = getEnvOrDefault("NOSTR_RELAYS", "wss://strfry.shock.network");
|
||||||
return {
|
return {
|
||||||
relays: EnvMustBeNonEmptyString("NOSTR_RELAYS").split(' ')
|
relays: relaysEnv.split(' ')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default class NostrSubprocess {
|
export default class NostrSubprocess {
|
||||||
settings: NostrSettings
|
settings: NostrSettings
|
||||||
childProcess: ChildProcess
|
childProcess: ChildProcess
|
||||||
|
|
@ -31,8 +38,8 @@ export default class NostrSubprocess {
|
||||||
this.childProcess.send(message)
|
this.childProcess.send(message)
|
||||||
}
|
}
|
||||||
|
|
||||||
Send(appId: string, data: SendData, relays?: string[]) {
|
Send(initiator: SendInitiator, data: SendData, relays?: string[]) {
|
||||||
this.sendToChildProcess({ type: 'send', data, appId, relays })
|
this.sendToChildProcess({ type: 'send', data, initiator, relays })
|
||||||
}
|
}
|
||||||
Stop() {
|
Stop() {
|
||||||
this.childProcess.kill()
|
this.childProcess.kill()
|
||||||
|
|
|
||||||
|
|
@ -26,9 +26,9 @@ export type DbSettings = {
|
||||||
}
|
}
|
||||||
export const LoadDbSettingsFromEnv = (): DbSettings => {
|
export const LoadDbSettingsFromEnv = (): DbSettings => {
|
||||||
return {
|
return {
|
||||||
databaseFile: EnvMustBeNonEmptyString("DATABASE_FILE"),
|
databaseFile: process.env.DATABASE_FILE || "db.sqlite",
|
||||||
migrate: process.env.MIGRATE_DB === 'true' || false,
|
migrate: process.env.MIGRATE_DB === 'true' || false,
|
||||||
metricsDatabaseFile: EnvMustBeNonEmptyString("METRICS_DATABASE_FILE")
|
metricsDatabaseFile: process.env.METRICS_DATABASE_FILE || "metrics.sqlite"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,7 @@ const columns = ["timestampMs", "userId", "appUserId", "appId", "balance", "type
|
||||||
type StringerWrite = (chunk: any, cb: (error: Error | null | undefined) => void) => boolean
|
type StringerWrite = (chunk: any, cb: (error: Error | null | undefined) => void) => boolean
|
||||||
export default class EventsLogManager {
|
export default class EventsLogManager {
|
||||||
eventLogPath: string
|
eventLogPath: string
|
||||||
log = getLogger({ appName: "EventsLogManager" })
|
log = getLogger({ component: "EventsLogManager" })
|
||||||
stringerWrite: StringerWrite
|
stringerWrite: StringerWrite
|
||||||
constructor(eventLogPath: string) {
|
constructor(eventLogPath: string) {
|
||||||
this.eventLogPath = eventLogPath
|
this.eventLogPath = eventLogPath
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,7 @@ export default class {
|
||||||
log: PubLogger
|
log: PubLogger
|
||||||
constructor(name: string, DB: DataSource | EntityManager) {
|
constructor(name: string, DB: DataSource | EntityManager) {
|
||||||
this.DB = DB
|
this.DB = DB
|
||||||
this.log = getLogger({ appName: name })
|
this.log = getLogger({ component: name })
|
||||||
}
|
}
|
||||||
|
|
||||||
PushToQueue<T>(op: TxOperation<T>) {
|
PushToQueue<T>(op: TxOperation<T>) {
|
||||||
|
|
|
||||||
|
|
@ -94,10 +94,10 @@ export default class {
|
||||||
user_id: userId,
|
user_id: userId,
|
||||||
}, "balance_sats", increment)
|
}, "balance_sats", increment)
|
||||||
if (!res.affected) {
|
if (!res.affected) {
|
||||||
getLogger({ userId: userId, appName: "balanceUpdates" })("user unaffected by increment")
|
getLogger({ userId: userId, component: "balanceUpdates" })("user unaffected by increment")
|
||||||
throw new Error("unaffected balance increment for " + userId) // TODO: fix logs doxing
|
throw new Error("unaffected balance increment for " + userId) // TODO: fix logs doxing
|
||||||
}
|
}
|
||||||
getLogger({ userId: userId, appName: "balanceUpdates" })("incremented balance from", user.balance_sats, "sats, by", increment, "sats")
|
getLogger({ userId: userId, component: "balanceUpdates" })("incremented balance from", user.balance_sats, "sats, by", increment, "sats")
|
||||||
this.eventsLog.LogEvent({ type: 'balance_increment', userId, appId: "", appUserId: "", balance: user.balance_sats, data: reason, amount: increment })
|
this.eventsLog.LogEvent({ type: 'balance_increment', userId, appId: "", appUserId: "", balance: user.balance_sats, data: reason, amount: increment })
|
||||||
}
|
}
|
||||||
async DecrementUserBalance(userId: string, decrement: number, reason: string, entityManager?: DataSource | EntityManager) {
|
async DecrementUserBalance(userId: string, decrement: number, reason: string, entityManager?: DataSource | EntityManager) {
|
||||||
|
|
@ -116,17 +116,17 @@ export default class {
|
||||||
async DecrementUserBalanceInTx(userId: string, decrement: number, reason: string, dbTx: DataSource | EntityManager) {
|
async DecrementUserBalanceInTx(userId: string, decrement: number, reason: string, dbTx: DataSource | EntityManager) {
|
||||||
const user = await this.GetUser(userId, dbTx)
|
const user = await this.GetUser(userId, dbTx)
|
||||||
if (!user || user.balance_sats < decrement) {
|
if (!user || user.balance_sats < decrement) {
|
||||||
getLogger({ userId: userId, appName: "balanceUpdates" })("not enough balance to decrement")
|
getLogger({ userId: userId, component: "balanceUpdates" })("not enough balance to decrement")
|
||||||
throw new Error("not enough balance to decrement")
|
throw new Error("not enough balance to decrement")
|
||||||
}
|
}
|
||||||
const res = await dbTx.getRepository(User).decrement({
|
const res = await dbTx.getRepository(User).decrement({
|
||||||
user_id: userId,
|
user_id: userId,
|
||||||
}, "balance_sats", decrement)
|
}, "balance_sats", decrement)
|
||||||
if (!res.affected) {
|
if (!res.affected) {
|
||||||
getLogger({ userId: userId, appName: "balanceUpdates" })("user unaffected by decrement")
|
getLogger({ userId: userId, component: "balanceUpdates" })("user unaffected by decrement")
|
||||||
throw new Error("unaffected balance decrement for " + userId) // TODO: fix logs doxing
|
throw new Error("unaffected balance decrement for " + userId) // TODO: fix logs doxing
|
||||||
}
|
}
|
||||||
getLogger({ userId: userId, appName: "balanceUpdates" })("decremented balance from", user.balance_sats, "sats, by", decrement, "sats")
|
getLogger({ userId: userId, component: "balanceUpdates" })("decremented balance from", user.balance_sats, "sats, by", decrement, "sats")
|
||||||
this.eventsLog.LogEvent({ type: 'balance_decrement', userId, appId: "", appUserId: "", balance: user.balance_sats, data: reason, amount: decrement })
|
this.eventsLog.LogEvent({ type: 'balance_decrement', userId, appId: "", appUserId: "", balance: user.balance_sats, data: reason, amount: decrement })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
54
src/tests/liquidityProvider.spec.ts
Normal file
54
src/tests/liquidityProvider.spec.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
import { disableLoggers } from '../services/helpers/logger.js'
|
||||||
|
import { runSanityCheck, safelySetUserBalance, TestBase, TestUserData } from './testBase.js'
|
||||||
|
import { initBootstrappedInstance } from './setupBootstrapped.js'
|
||||||
|
import Main from '../services/main/index.js'
|
||||||
|
import { AppData } from '../services/main/init.js'
|
||||||
|
export const ignore = false
|
||||||
|
export const dev = false
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export default async (T: TestBase) => {
|
||||||
|
disableLoggers([], ["EventsLogManager", "watchdog", "htlcTracker", "debugHtlcs", "debugLndBalancev3", "metrics", "mainForTest", "main"])
|
||||||
|
await safelySetUserBalance(T, T.user1, 2000)
|
||||||
|
T.d("starting liquidityProvider tests...")
|
||||||
|
const { bootstrapped, bootstrappedUser, stop } = await initBootstrappedInstance(T)
|
||||||
|
await testInboundPaymentFromProvider(T, bootstrapped, bootstrappedUser)
|
||||||
|
await testOutboundPaymentFromProvider(T, bootstrapped, bootstrappedUser)
|
||||||
|
stop()
|
||||||
|
await runSanityCheck(T)
|
||||||
|
}
|
||||||
|
|
||||||
|
const testInboundPaymentFromProvider = async (T: TestBase, bootstrapped: Main, bUser: TestUserData) => {
|
||||||
|
T.d("starting testInboundPaymentFromProvider")
|
||||||
|
const invoiceRes = await bootstrapped.appUserManager.NewInvoice({ app_id: bUser.appId, user_id: bUser.userId, app_user_id: bUser.appUserIdentifier }, { amountSats: 2000, memo: "liquidityTest" })
|
||||||
|
|
||||||
|
await T.externalAccessToOtherLnd.PayInvoice(invoiceRes.invoice, 0, 100)
|
||||||
|
const userBalance = await bootstrapped.appUserManager.GetUserInfo({ app_id: bUser.appId, user_id: bUser.userId, app_user_id: bUser.appUserIdentifier })
|
||||||
|
T.expect(userBalance.balance).to.equal(2000)
|
||||||
|
|
||||||
|
const providerBalance = await bootstrapped.liquidProvider.CheckUserState()
|
||||||
|
if (!providerBalance) {
|
||||||
|
throw new Error("provider balance not found")
|
||||||
|
}
|
||||||
|
T.expect(providerBalance.balance).to.equal(2000)
|
||||||
|
T.d("testInboundPaymentFromProvider done")
|
||||||
|
}
|
||||||
|
|
||||||
|
const testOutboundPaymentFromProvider = async (T: TestBase, bootstrapped: Main, bootstrappedUser: TestUserData) => {
|
||||||
|
T.d("starting testOutboundPaymentFromProvider")
|
||||||
|
|
||||||
|
const invoice = await T.externalAccessToOtherLnd.NewInvoice(1000, "", 60 * 60)
|
||||||
|
const ctx = { app_id: bootstrappedUser.appId, user_id: bootstrappedUser.userId, app_user_id: bootstrappedUser.appUserIdentifier }
|
||||||
|
const res = await bootstrapped.appUserManager.PayInvoice(ctx, { invoice: invoice.payRequest, amount: 0 })
|
||||||
|
|
||||||
|
const userBalance = await bootstrapped.appUserManager.GetUserInfo(ctx)
|
||||||
|
T.expect(userBalance.balance).to.equal(986) // 2000 - (1000 + 6(x2) + 2)
|
||||||
|
|
||||||
|
const providerBalance = await bootstrapped.liquidProvider.CheckUserState()
|
||||||
|
if (!providerBalance) {
|
||||||
|
throw new Error("provider balance not found")
|
||||||
|
}
|
||||||
|
T.expect(providerBalance.balance).to.equal(992) // 2000 - (1000 + 6 +2)
|
||||||
|
T.d("testOutboundPaymentFromProvider done")
|
||||||
|
}
|
||||||
|
|
@ -1,14 +1,15 @@
|
||||||
import { LoadTestSettingsFromEnv } from "../services/main/settings.js"
|
import { LoadTestSettingsFromEnv } from "../services/main/settings.js"
|
||||||
import { BitcoinCoreWrapper } from "./bitcoinCore.js"
|
import { BitcoinCoreWrapper } from "./bitcoinCore.js"
|
||||||
import LND from '../services/lnd/lnd.js'
|
import LND from '../services/lnd/lnd.js'
|
||||||
|
import { LiquidityProvider } from "../services/lnd/liquidityProvider.js"
|
||||||
|
|
||||||
export const setupNetwork = async () => {
|
export const setupNetwork = async () => {
|
||||||
const settings = LoadTestSettingsFromEnv()
|
const settings = LoadTestSettingsFromEnv()
|
||||||
const core = new BitcoinCoreWrapper(settings)
|
const core = new BitcoinCoreWrapper(settings)
|
||||||
await core.InitAddress()
|
await core.InitAddress()
|
||||||
await core.Mine(1)
|
await core.Mine(1)
|
||||||
const alice = new LND(settings.lndSettings, () => { }, () => { }, () => { }, () => { })
|
const alice = new LND(settings.lndSettings, new LiquidityProvider("", () => { }), () => { }, () => { }, () => { }, () => { })
|
||||||
const bob = new LND({ ...settings.lndSettings, mainNode: settings.lndSettings.otherNode }, () => { }, () => { }, () => { }, () => { })
|
const bob = new LND({ ...settings.lndSettings, mainNode: settings.lndSettings.otherNode }, new LiquidityProvider("", () => { }), () => { }, () => { }, () => { }, () => { })
|
||||||
await tryUntil<void>(async i => {
|
await tryUntil<void>(async i => {
|
||||||
const peers = await alice.ListPeers()
|
const peers = await alice.ListPeers()
|
||||||
if (peers.peers.length > 0) {
|
if (peers.peers.length > 0) {
|
||||||
|
|
@ -46,6 +47,9 @@ export const setupNetwork = async () => {
|
||||||
throw new Error("bob not synced to graph")
|
throw new Error("bob not synced to graph")
|
||||||
}
|
}
|
||||||
}, 15, 2000)
|
}, 15, 2000)
|
||||||
|
|
||||||
|
alice.Stop()
|
||||||
|
bob.Stop()
|
||||||
}
|
}
|
||||||
|
|
||||||
const tryUntil = async <T>(fn: (attempt: number) => Promise<T>, maxTries: number, interval: number) => {
|
const tryUntil = async <T>(fn: (attempt: number) => Promise<T>, maxTries: number, interval: number) => {
|
||||||
|
|
|
||||||
92
src/tests/setupBootstrapped.ts
Normal file
92
src/tests/setupBootstrapped.ts
Normal file
|
|
@ -0,0 +1,92 @@
|
||||||
|
import { getLogger } from '../services/helpers/logger.js'
|
||||||
|
import { initMainHandler } from '../services/main/init.js'
|
||||||
|
import { LoadTestSettingsFromEnv } from '../services/main/settings.js'
|
||||||
|
import { SendData } from '../services/nostr/handler.js'
|
||||||
|
import { TestBase, TestUserData } from './testBase.js'
|
||||||
|
import * as Types from '../../proto/autogenerated/ts/types.js'
|
||||||
|
|
||||||
|
export const initBootstrappedInstance = async (T: TestBase) => {
|
||||||
|
const settings = LoadTestSettingsFromEnv()
|
||||||
|
settings.lndSettings.useOnlyLiquidityProvider = true
|
||||||
|
settings.lndSettings.liquidityProviderPub = T.app.publicKey
|
||||||
|
settings.lndSettings.mainNode = settings.lndSettings.thirdNode
|
||||||
|
const initialized = await initMainHandler(getLogger({ component: "bootstrapped" }), settings)
|
||||||
|
if (!initialized) {
|
||||||
|
throw new Error("failed to initialize bootstrapped main handler")
|
||||||
|
}
|
||||||
|
const { mainHandler: bootstrapped, liquidityProviderInfo, liquidityProviderApp } = initialized
|
||||||
|
T.main.attachNostrSend(async (_, data, r) => {
|
||||||
|
if (data.type === 'event') {
|
||||||
|
throw new Error("unsupported event type")
|
||||||
|
}
|
||||||
|
if (data.pub !== liquidityProviderInfo.publicKey) {
|
||||||
|
throw new Error("invalid pub " + data.pub + " expected " + liquidityProviderInfo.publicKey)
|
||||||
|
}
|
||||||
|
const j = JSON.parse(data.content) as { requestId: string }
|
||||||
|
console.log("sending new operation to provider")
|
||||||
|
bootstrapped.liquidProvider.onEvent(j, T.app.publicKey)
|
||||||
|
})
|
||||||
|
bootstrapped.liquidProvider.attachNostrSend(async (_, data, r) => {
|
||||||
|
const res = await handleSend(T, data)
|
||||||
|
if (data.type === 'event') {
|
||||||
|
throw new Error("unsupported event type")
|
||||||
|
}
|
||||||
|
if (!res) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
bootstrapped.liquidProvider.onEvent(res, data.pub)
|
||||||
|
})
|
||||||
|
bootstrapped.liquidProvider.setNostrInfo({ clientId: liquidityProviderInfo.clientId, myPub: liquidityProviderInfo.publicKey })
|
||||||
|
await new Promise<void>(res => {
|
||||||
|
const interval = setInterval(() => {
|
||||||
|
if (bootstrapped.liquidProvider.CanProviderHandle({ action: 'receive', amount: 2000 })) {
|
||||||
|
clearInterval(interval)
|
||||||
|
res()
|
||||||
|
} else {
|
||||||
|
console.log("waiting for provider to be able to handle the request")
|
||||||
|
}
|
||||||
|
}, 500)
|
||||||
|
})
|
||||||
|
const bUser = await bootstrapped.applicationManager.AddAppUser(liquidityProviderApp.appId, { identifier: "user1_bootstrapped", balance: 0, fail_if_exists: true })
|
||||||
|
const bootstrappedUser: TestUserData = { userId: bUser.info.userId, appUserIdentifier: bUser.identifier, appId: liquidityProviderApp.appId }
|
||||||
|
return {
|
||||||
|
bootstrapped, liquidityProviderInfo, liquidityProviderApp, bootstrappedUser, stop: () => {
|
||||||
|
bootstrapped.Stop()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
type TransportRequest = { requestId: string, authIdentifier: string } & (
|
||||||
|
{ rpcName: 'GetUserInfo' } |
|
||||||
|
{ rpcName: 'NewInvoice', body: Types.NewInvoiceRequest } |
|
||||||
|
{ rpcName: 'PayInvoice', body: Types.PayInvoiceRequest } |
|
||||||
|
{ rpcName: 'GetLiveUserOperations' } |
|
||||||
|
{ rpcName: "" }
|
||||||
|
)
|
||||||
|
const handleSend = async (T: TestBase, data: SendData) => {
|
||||||
|
if (data.type === 'event') {
|
||||||
|
throw new Error("unsupported event type")
|
||||||
|
}
|
||||||
|
if (data.pub !== T.app.publicKey) {
|
||||||
|
throw new Error("invalid pub")
|
||||||
|
}
|
||||||
|
const j = JSON.parse(data.content) as TransportRequest
|
||||||
|
const app = await T.main.storage.applicationStorage.GetApplication(T.app.appId)
|
||||||
|
const nostrUser = await T.main.storage.applicationStorage.GetOrCreateNostrAppUser(app, j.authIdentifier)
|
||||||
|
const userCtx = { app_id: app.app_id, user_id: nostrUser.user.user_id, app_user_id: nostrUser.identifier }
|
||||||
|
switch (j.rpcName) {
|
||||||
|
case 'GetUserInfo':
|
||||||
|
const infoRes = await T.main.appUserManager.GetUserInfo(userCtx)
|
||||||
|
return { ...infoRes, status: "OK", requestId: j.requestId }
|
||||||
|
case 'NewInvoice':
|
||||||
|
const genInvoiceRes = await T.main.appUserManager.NewInvoice(userCtx, j.body)
|
||||||
|
return { ...genInvoiceRes, status: "OK", requestId: j.requestId }
|
||||||
|
case 'PayInvoice':
|
||||||
|
const payRes = await T.main.appUserManager.PayInvoice(userCtx, j.body)
|
||||||
|
return { ...payRes, status: "OK", requestId: j.requestId }
|
||||||
|
case 'GetLiveUserOperations':
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
console.log(data)
|
||||||
|
throw new Error("unsupported rpcName " + j.rpcName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -4,7 +4,7 @@ import { Describe, expect, expectThrowsAsync, runSanityCheck, safelySetUserBalan
|
||||||
export const ignore = false
|
export const ignore = false
|
||||||
|
|
||||||
export default async (T: TestBase) => {
|
export default async (T: TestBase) => {
|
||||||
disableLoggers(["EventsLogManager", "htlcTracker", "watchdog"])
|
disableLoggers([], ["EventsLogManager", "htlcTracker", "watchdog"])
|
||||||
await safelySetUserBalance(T, T.user1, 2000)
|
await safelySetUserBalance(T, T.user1, 2000)
|
||||||
await testSpamExternalPayment(T)
|
await testSpamExternalPayment(T)
|
||||||
await runSanityCheck(T)
|
await runSanityCheck(T)
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ import * as Types from '../../proto/autogenerated/ts/types.js'
|
||||||
export const ignore = false
|
export const ignore = false
|
||||||
|
|
||||||
export default async (T: TestBase) => {
|
export default async (T: TestBase) => {
|
||||||
disableLoggers(["EventsLogManager", "htlcTracker", "watchdog"])
|
disableLoggers([], ["EventsLogManager", "htlcTracker", "watchdog"])
|
||||||
await safelySetUserBalance(T, T.user1, 2000)
|
await safelySetUserBalance(T, T.user1, 2000)
|
||||||
await testSpamExternalPayment(T)
|
await testSpamExternalPayment(T)
|
||||||
await runSanityCheck(T)
|
await runSanityCheck(T)
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,8 @@ import chaiString from 'chai-string'
|
||||||
import { defaultInvoiceExpiry } from '../services/storage/paymentStorage.js'
|
import { defaultInvoiceExpiry } from '../services/storage/paymentStorage.js'
|
||||||
import SanityChecker from '../services/main/sanityChecker.js'
|
import SanityChecker from '../services/main/sanityChecker.js'
|
||||||
import LND from '../services/lnd/lnd.js'
|
import LND from '../services/lnd/lnd.js'
|
||||||
|
import { getLogger, resetDisabledLoggers } from '../services/helpers/logger.js'
|
||||||
|
import { LiquidityProvider } from '../services/lnd/liquidityProvider.js'
|
||||||
chai.use(chaiString)
|
chai.use(chaiString)
|
||||||
export const expect = chai.expect
|
export const expect = chai.expect
|
||||||
export type Describe = (message: string, failure?: boolean) => void
|
export type Describe = (message: string, failure?: boolean) => void
|
||||||
|
|
@ -32,7 +34,7 @@ export type TestBase = {
|
||||||
|
|
||||||
export const SetupTest = async (d: Describe): Promise<TestBase> => {
|
export const SetupTest = async (d: Describe): Promise<TestBase> => {
|
||||||
const settings = LoadTestSettingsFromEnv()
|
const settings = LoadTestSettingsFromEnv()
|
||||||
const initialized = await initMainHandler(console.log, settings)
|
const initialized = await initMainHandler(getLogger({ component: "mainForTest" }), settings)
|
||||||
if (!initialized) {
|
if (!initialized) {
|
||||||
throw new Error("failed to initialize main handler")
|
throw new Error("failed to initialize main handler")
|
||||||
}
|
}
|
||||||
|
|
@ -44,15 +46,15 @@ export const SetupTest = async (d: Describe): Promise<TestBase> => {
|
||||||
const user2 = { userId: u2.info.userId, appUserIdentifier: u2.identifier, appId: app.appId }
|
const user2 = { userId: u2.info.userId, appUserIdentifier: u2.identifier, appId: app.appId }
|
||||||
|
|
||||||
|
|
||||||
const externalAccessToMainLnd = new LND(settings.lndSettings, console.log, console.log, () => { }, () => { })
|
const externalAccessToMainLnd = new LND(settings.lndSettings, new LiquidityProvider("", () => { }), console.log, console.log, () => { }, () => { })
|
||||||
await externalAccessToMainLnd.Warmup()
|
await externalAccessToMainLnd.Warmup()
|
||||||
|
|
||||||
const otherLndSetting = { ...settings.lndSettings, mainNode: settings.lndSettings.otherNode }
|
const otherLndSetting = { ...settings.lndSettings, mainNode: settings.lndSettings.otherNode }
|
||||||
const externalAccessToOtherLnd = new LND(otherLndSetting, console.log, console.log, () => { }, () => { })
|
const externalAccessToOtherLnd = new LND(otherLndSetting, new LiquidityProvider("", () => { }), console.log, console.log, () => { }, () => { })
|
||||||
await externalAccessToOtherLnd.Warmup()
|
await externalAccessToOtherLnd.Warmup()
|
||||||
|
|
||||||
const thirdLndSetting = { ...settings.lndSettings, mainNode: settings.lndSettings.thirdNode }
|
const thirdLndSetting = { ...settings.lndSettings, mainNode: settings.lndSettings.thirdNode }
|
||||||
const externalAccessToThirdLnd = new LND(thirdLndSetting, console.log, console.log, () => { }, () => { })
|
const externalAccessToThirdLnd = new LND(thirdLndSetting, new LiquidityProvider("", () => { }), console.log, console.log, () => { }, () => { })
|
||||||
await externalAccessToThirdLnd.Warmup()
|
await externalAccessToThirdLnd.Warmup()
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -69,6 +71,7 @@ export const teardown = async (T: TestBase) => {
|
||||||
T.externalAccessToMainLnd.Stop()
|
T.externalAccessToMainLnd.Stop()
|
||||||
T.externalAccessToOtherLnd.Stop()
|
T.externalAccessToOtherLnd.Stop()
|
||||||
T.externalAccessToThirdLnd.Stop()
|
T.externalAccessToThirdLnd.Stop()
|
||||||
|
resetDisabledLoggers()
|
||||||
console.log("teardown")
|
console.log("teardown")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
|
|
||||||
import { globby } from 'globby'
|
import { globby } from 'globby'
|
||||||
import { setupNetwork } from './networkSetup.js'
|
import { setupNetwork } from './networkSetup.js'
|
||||||
import { Describe, SetupTest, teardown, TestBase } from './testBase.js'
|
import { Describe, SetupTest, teardown, TestBase } from './testBase.js'
|
||||||
|
|
||||||
type TestModule = {
|
type TestModule = {
|
||||||
ignore?: boolean
|
ignore?: boolean
|
||||||
dev?: boolean
|
dev?: boolean
|
||||||
|
|
|
||||||
18
src/tests/userPayment.spec.ts
Normal file
18
src/tests/userPayment.spec.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
import { defaultInvoiceExpiry } from '../services/storage/paymentStorage.js'
|
||||||
|
import { runSanityCheck, safelySetUserBalance, TestBase } from './testBase.js'
|
||||||
|
export const ignore = false
|
||||||
|
export const dev = false
|
||||||
|
|
||||||
|
export default async (T: TestBase) => {
|
||||||
|
await safelySetUserBalance(T, T.user1, 2000)
|
||||||
|
await testSuccessfulUserPaymentToExternalNode(T)
|
||||||
|
await testSuccessfulUserPaymentToExternalNode(T)
|
||||||
|
await runSanityCheck(T)
|
||||||
|
}
|
||||||
|
|
||||||
|
const testSuccessfulUserPaymentToExternalNode = async (T: TestBase) => {
|
||||||
|
T.d("starting testSuccessfulUserPaymentToExternalNode")
|
||||||
|
const invoice = await T.externalAccessToOtherLnd.NewInvoice(500, "test", defaultInvoiceExpiry)
|
||||||
|
const payment = await T.main.appUserManager.PayInvoice({ app_id: T.user1.appId, user_id: T.user1.userId, app_user_id: T.user1.appUserIdentifier }, { invoice: invoice.payRequest, amount: 0 })
|
||||||
|
T.d("paid 500 sats invoice from user1 to external node")
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue