commit
f316cafb46
135 changed files with 37946 additions and 14766 deletions
10
.babelrc
10
.babelrc
|
|
@ -1,10 +0,0 @@
|
|||
{
|
||||
"env": {
|
||||
"test": {
|
||||
"plugins": [
|
||||
"transform-es2015-modules-commonjs",
|
||||
"@babel/plugin-proposal-class-properties"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
**/.git
|
||||
**/node_modules
|
||||
**/radata
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
# pub and nostr peers
|
||||
PEERS=["https://wut.shock.network"]
|
||||
# API Device Token
|
||||
MS_TO_TOKEN_EXPIRATION=4500000
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
*.ts
|
||||
/public/*.min.js
|
||||
105
.eslintrc.json
105
.eslintrc.json
|
|
@ -1,105 +0,0 @@
|
|||
{
|
||||
"extends": ["eslint:all", "prettier", "plugin:mocha/recommended"],
|
||||
"plugins": ["prettier", "mocha", "babel"],
|
||||
"rules": {
|
||||
"prettier/prettier": "error",
|
||||
"strict": "off",
|
||||
|
||||
"mocha/no-mocha-arrows": "off",
|
||||
|
||||
"max-statements-per-line": "off",
|
||||
|
||||
"no-empty-function": "off",
|
||||
|
||||
"no-console": "off",
|
||||
|
||||
"max-statements": "off",
|
||||
|
||||
"global-require": "off",
|
||||
|
||||
"new-cap": "off",
|
||||
|
||||
"one-var": "off",
|
||||
|
||||
"max-lines-per-function": "off",
|
||||
|
||||
"no-underscore-dangle": "off",
|
||||
|
||||
"no-implicit-coercion": "off",
|
||||
|
||||
"no-magic-numbers": "off",
|
||||
|
||||
"no-negated-condition": "off",
|
||||
|
||||
"capitalized-comments": "off",
|
||||
|
||||
"max-params": "off",
|
||||
|
||||
"multiline-comment-style": "off",
|
||||
|
||||
"spaced-comment": "off",
|
||||
|
||||
"no-inline-comments": "off",
|
||||
|
||||
"sort-keys": "off",
|
||||
|
||||
"max-lines": "off",
|
||||
|
||||
"prefer-template": "off",
|
||||
|
||||
"callback-return": "off",
|
||||
|
||||
"no-ternary": "off",
|
||||
|
||||
"no-invalid-this": "off",
|
||||
|
||||
"babel/no-invalid-this": "error",
|
||||
|
||||
"complexity": "off",
|
||||
|
||||
"yoda": "off",
|
||||
|
||||
"prefer-promise-reject-errors": "off",
|
||||
|
||||
"camelcase": "off",
|
||||
|
||||
"consistent-return": "off",
|
||||
|
||||
"no-shadow": "off",
|
||||
// We're usually throwing objects throughout the API to allow for more detailed error messages
|
||||
"no-throw-literal": "off",
|
||||
|
||||
// lightning has sync methods and this rule bans them
|
||||
"no-sync": "off",
|
||||
|
||||
"id-length": "off",
|
||||
|
||||
// typescript does this
|
||||
"no-unused-vars": "off",
|
||||
|
||||
// https://github.com/prettier/eslint-config-prettier/issues/132
|
||||
"line-comment-position": "off",
|
||||
|
||||
// if someone does this it's probably intentional
|
||||
"no-useless-concat": "off",
|
||||
|
||||
"no-plusplus": "off",
|
||||
|
||||
"no-undefined": "off",
|
||||
|
||||
"no-process-env": "off",
|
||||
|
||||
// I am now convinced TODO comments closer to the relevant code are better
|
||||
// than GH issues. Especially when it only concerns a single function /
|
||||
// routine.
|
||||
"no-warning-comments": "off",
|
||||
|
||||
// broken
|
||||
"sort-imports": "off"
|
||||
},
|
||||
"parser": "babel-eslint",
|
||||
"env": {
|
||||
"node": true,
|
||||
"es6": true
|
||||
}
|
||||
}
|
||||
2
.gitattributes
vendored
2
.gitattributes
vendored
|
|
@ -1,2 +0,0 @@
|
|||
# Auto detect text files and perform LF normalization
|
||||
* text=auto
|
||||
30
.github/dependabot.yml
vendored
30
.github/dependabot.yml
vendored
|
|
@ -1,30 +0,0 @@
|
|||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: npm
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: daily
|
||||
open-pull-requests-limit: 10
|
||||
ignore:
|
||||
- dependency-name: bitcore-lib
|
||||
versions:
|
||||
- 8.24.2
|
||||
- 8.25.0
|
||||
- 8.25.2
|
||||
- 8.25.3
|
||||
- 8.25.4
|
||||
- 8.25.7
|
||||
- 9.0.0
|
||||
- dependency-name: socket.io
|
||||
versions:
|
||||
- 3.1.0
|
||||
- dependency-name: commander
|
||||
versions:
|
||||
- 7.0.0
|
||||
- 7.1.0
|
||||
- dependency-name: lint-staged
|
||||
versions:
|
||||
- 10.5.3
|
||||
- dependency-name: eslint-plugin-prettier
|
||||
versions:
|
||||
- 3.3.1
|
||||
40
.github/workflows/dockerhub.yml
vendored
40
.github/workflows/dockerhub.yml
vendored
|
|
@ -1,40 +0,0 @@
|
|||
name: Publish Docker image
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
jobs:
|
||||
push_to_registry:
|
||||
name: Push Docker image to Docker Hub
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out the repo
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v1
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v1
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
|
||||
with:
|
||||
images: shockwallet/api
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@ad44023a93711e3deb337508980b4b5e9bcdc5dc
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
40
.github/workflows/main.yml
vendored
40
.github/workflows/main.yml
vendored
|
|
@ -1,40 +0,0 @@
|
|||
name: Update Wizard
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ 'master' ]
|
||||
pull_request:
|
||||
branches: [ 'master' ]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
name:
|
||||
description: 'Bump Wizard Version'
|
||||
required: false
|
||||
default: 'yes'
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
strategy:
|
||||
matrix:
|
||||
repo: ['shocknet/Wizard']
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 🛎️ Checkout
|
||||
uses: actions/checkout@v2.3.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
ref: ${{ github.ref }}
|
||||
|
||||
- name: ⚙️ Install Dependencies
|
||||
run: yarn install
|
||||
|
||||
- name: 📝 Run Tests
|
||||
run: yarn test
|
||||
|
||||
- name: 📯 Repository Dispatch
|
||||
uses: peter-evans/repository-dispatch@v1
|
||||
with:
|
||||
token: ${{ secrets.REPO_ACCESS_TOKEN }}
|
||||
repository: ${{ matrix.repo }}
|
||||
event-type: api-update
|
||||
client-payload: '{"ref": "${{ github.ref }}", "sha": "${{ github.sha }}"}'
|
||||
36
.github/workflows/version.yml
vendored
36
.github/workflows/version.yml
vendored
|
|
@ -1,36 +0,0 @@
|
|||
name: Bump "package.json" Version
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [prereleased, released]
|
||||
|
||||
jobs:
|
||||
version-bump:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@master
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0 # otherwise, you will failed to push refs to dest repo
|
||||
- name: Get the last API TAG and current version in package.json
|
||||
run: |
|
||||
export RELEASE_TAG=$(git describe --tags --abbrev=0) && \
|
||||
echo "VERSION=${RELEASE_TAG}" >> $GITHUB_ENV
|
||||
|
||||
export API_TAG=$(cat ./package.json | jq -r '.version')
|
||||
|
||||
echo $(if [ "$API_TAG" = "$RELEASE_TAG" ]; then echo "UPGRADEABLE=false"; else echo "UPGRADEABLE=true"; fi) >> $GITHUB_ENV
|
||||
|
||||
- name: Update and Commit files
|
||||
if: ${{ env.UPGRADEABLE == 'true' }}
|
||||
run: |
|
||||
cat ./package.json | jq -r --arg API_TAG "${{ env.VERSION }}" '.version = $API_TAG' | tee a.json && mv a.json package.json
|
||||
git config --local user.email "actions@shock.network"
|
||||
git config --local user.name "Version Update Action"
|
||||
git commit -m "version upgraded to ${{ env.VERSION }}" -a
|
||||
- name: Push changes
|
||||
if: ${{ env.UPGRADEABLE == 'true' }}
|
||||
uses: ad-m/github-push-action@master
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
branch: master
|
||||
33
.gitignore
vendored
33
.gitignore
vendored
|
|
@ -1,25 +1,10 @@
|
|||
node_modules
|
||||
.storage
|
||||
services/auth/secrets.json
|
||||
.idea/
|
||||
.vscode/
|
||||
node_modules/
|
||||
build/
|
||||
tmp/
|
||||
temp/
|
||||
.env
|
||||
*.log
|
||||
# New logger date format
|
||||
*.log.*
|
||||
.directory
|
||||
.DS_Store
|
||||
|
||||
test-radata/
|
||||
radata/
|
||||
radata-*.tmp
|
||||
*.cert
|
||||
*.key
|
||||
|
||||
*-audit.json
|
||||
# Yarn v2
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/sdks
|
||||
!.yarn/versions
|
||||
build/
|
||||
db.sqlite
|
||||
.key/
|
||||
1
.nvmrc
1
.nvmrc
|
|
@ -1 +0,0 @@
|
|||
v14.18.3
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
{
|
||||
"requirePragma": true,
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"endOfLine": "auto"
|
||||
}
|
||||
77
.vscode/launch.json
vendored
77
.vscode/launch.json
vendored
|
|
@ -1,77 +0,0 @@
|
|||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Attach",
|
||||
"port": 9229,
|
||||
"request": "attach",
|
||||
"skipFiles": ["<node_internals>/**"],
|
||||
"type": "pwa-node"
|
||||
},
|
||||
{
|
||||
"name": "Nodemon",
|
||||
"program": "${workspaceFolder}/main.js",
|
||||
"args": ["--", "-h", "0.0.0.0", "-c"],
|
||||
"request": "launch",
|
||||
"skipFiles": ["<node_internals>/**"],
|
||||
"type": "node",
|
||||
"envFile": "${workspaceFolder}/.env",
|
||||
"outputCapture": "std",
|
||||
|
||||
// https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_restarting-debug-sessions-automatically-when-source-is-edited
|
||||
// Tip: Pressing the Stop button stops the debug session and disconnects
|
||||
// from Node.js, but nodemon (and Node.js) will continue to run. To stop
|
||||
// nodemon, you will have to kill it from the command line (which is
|
||||
// easily possible if you use the integratedTerminal as shown above).
|
||||
|
||||
// Tip: In case of syntax errors, nodemon will not be able to start
|
||||
// Node.js successfully until the error has been fixed. In this case, VS
|
||||
// Code will continue trying to attach to Node.js but eventually give up
|
||||
// (after 10 seconds). To avoid this, you can increase the timeout by
|
||||
// adding a timeout attribute with a larger value (in milliseconds).
|
||||
|
||||
"runtimeExecutable": "${workspaceFolder}/node_modules/nodemon/bin/nodemon.js",
|
||||
"console": "integratedTerminal",
|
||||
"internalConsoleOptions": "neverOpen",
|
||||
"restart": true
|
||||
},
|
||||
{
|
||||
"name": "Nodemon+Polar",
|
||||
"program": "${workspaceFolder}/main.js",
|
||||
"args": [
|
||||
"--",
|
||||
"-h",
|
||||
"0.0.0.0",
|
||||
"--trace-warnings",
|
||||
"--max-old-space-size=4096",
|
||||
"-c",
|
||||
"-d",
|
||||
"C:\\Users\\Predator\\AppData\\Local\\Lnd\\tls.cert",
|
||||
"-m",
|
||||
"C:\\Users\\Predator\\AppData\\Local\\Lnd\\data\\chain\\bitcoin\\mainnet\\admin.macaroon",
|
||||
"--tunnel"
|
||||
],
|
||||
"request": "launch",
|
||||
"skipFiles": ["<node_internals>/**"],
|
||||
"type": "node",
|
||||
"envFile": "${workspaceFolder}/.env",
|
||||
"outputCapture": "std",
|
||||
|
||||
// https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_restarting-debug-sessions-automatically-when-source-is-edited
|
||||
// Tip: Pressing the Stop button stops the debug session and disconnects
|
||||
// from Node.js, but nodemon (and Node.js) will continue to run. To stop
|
||||
// nodemon, you will have to kill it from the command line (which is
|
||||
// easily possible if you use the integratedTerminal as shown above).
|
||||
|
||||
// Tip: In case of syntax errors, nodemon will not be able to start
|
||||
// Node.js successfully until the error has been fixed. In this case, VS
|
||||
// Code will continue trying to attach to Node.js but eventually give up
|
||||
// (after 10 seconds). To avoid this, you can increase the timeout by
|
||||
// adding a timeout attribute with a larger value (in milliseconds).
|
||||
|
||||
"runtimeExecutable": "${workspaceFolder}/node_modules/nodemon/bin/nodemon.js",
|
||||
"console": "integratedTerminal",
|
||||
"internalConsoleOptions": "neverOpen",
|
||||
"restart": true
|
||||
}
|
||||
]
|
||||
}
|
||||
83
.vscode/settings.json
vendored
83
.vscode/settings.json
vendored
|
|
@ -1,83 +0,0 @@
|
|||
{
|
||||
"eslint.enable": true,
|
||||
"typescript.tsdk": "node_modules/typescript/lib",
|
||||
"debug.node.autoAttach": "on",
|
||||
"editor.formatOnSave": true,
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode",
|
||||
"cSpell.words": [
|
||||
"acked",
|
||||
"addinvoice",
|
||||
"Authing",
|
||||
"channelbalance",
|
||||
"ciphertext",
|
||||
"closechannel",
|
||||
"closedchannels",
|
||||
"Cltv",
|
||||
"connectpeer",
|
||||
"disconnectpeer",
|
||||
"eccrypto",
|
||||
"endregion",
|
||||
"ephem",
|
||||
"epriv",
|
||||
"Epub",
|
||||
"estimatefee",
|
||||
"estimateroutefee",
|
||||
"exportallchanbackups",
|
||||
"exportchanbackup",
|
||||
"falsey",
|
||||
"forwardinghistory",
|
||||
"getchaninfo",
|
||||
"getinfo",
|
||||
"getnetworkinfo",
|
||||
"getnodeinfo",
|
||||
"GUNRPC",
|
||||
"Healthz",
|
||||
"initwall",
|
||||
"ISEA",
|
||||
"keysend",
|
||||
"kubernetes",
|
||||
"listchannels",
|
||||
"listinvoices",
|
||||
"listpayments",
|
||||
"listpeers",
|
||||
"listunspent",
|
||||
"lndchanbackups",
|
||||
"LNDRPC",
|
||||
"lndstreaming",
|
||||
"lnrpc",
|
||||
"lres",
|
||||
"msgpack",
|
||||
"newaddress",
|
||||
"openchannel",
|
||||
"otheruser",
|
||||
"payreq",
|
||||
"pendingchannels",
|
||||
"preimage",
|
||||
"PUBKEY",
|
||||
"qrcode",
|
||||
"queryroute",
|
||||
"radata",
|
||||
"Reqs",
|
||||
"resave",
|
||||
"satoshis",
|
||||
"sendcoins",
|
||||
"sendmany",
|
||||
"sendpayment",
|
||||
"sendtoroute",
|
||||
"serverhost",
|
||||
"serverport",
|
||||
"shockping",
|
||||
"SHOCKWALLET",
|
||||
"signmessage",
|
||||
"thenables",
|
||||
"trackpayment",
|
||||
"txid",
|
||||
"unfollow",
|
||||
"Unlocker",
|
||||
"unsubscription",
|
||||
"utxos",
|
||||
"uuidv",
|
||||
"verifymessage",
|
||||
"walletbalance"
|
||||
]
|
||||
}
|
||||
33
.vscode/snippets.code-snippets
vendored
33
.vscode/snippets.code-snippets
vendored
|
|
@ -1,33 +0,0 @@
|
|||
{
|
||||
// Place your api workspace snippets here. Each snippet is defined under a
|
||||
// snippet name and has a scope, prefix, body and description. Add comma
|
||||
// separated ids of the languages where the snippet is applicable in the scope
|
||||
// field. If scope is left empty or omitted, the snippet gets applied to all
|
||||
// languages. The prefix is what is used to trigger the snippet and the body
|
||||
// will be expanded and inserted. Possible variables are: $1, $2 for tab
|
||||
// stops, $0 for the final cursor position, and ${1:label}, ${2:another} for
|
||||
// placeholders. Placeholders with the same ids are connected. Example: "Print
|
||||
// to console": {"scope": "javascript,typescript", "prefix": "log", "body":
|
||||
// ["console.log('$1');", "$2"
|
||||
// ],
|
||||
// "description": "Log output to console"
|
||||
// }
|
||||
|
||||
"Route Body": {
|
||||
"body": [
|
||||
"try {",
|
||||
" return res.json({",
|
||||
"",
|
||||
" })",
|
||||
"} catch (e) {",
|
||||
" console.log(e)",
|
||||
" return res.status(500).json({",
|
||||
" errorMessage: e.message",
|
||||
" })",
|
||||
"}"
|
||||
],
|
||||
"description": "Route Body",
|
||||
"prefix": "rbody",
|
||||
"scope": "javascript"
|
||||
}
|
||||
}
|
||||
18
Dockerfile
18
Dockerfile
|
|
@ -1,18 +0,0 @@
|
|||
FROM node:14-buster-slim
|
||||
|
||||
EXPOSE 9835
|
||||
|
||||
VOLUME [ "/root/.lnd", "/data" ]
|
||||
RUN apt-get update && apt-get install -y apt-transport-https git
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
ADD ./package.json /app/package.json
|
||||
ADD ./yarn.lock /app/yarn.lock
|
||||
|
||||
RUN yarn
|
||||
|
||||
ADD . /app
|
||||
|
||||
ENTRYPOINT [ "node", "main.js" ]
|
||||
688
LICENSE
688
LICENSE
|
|
@ -1,688 +0,0 @@
|
|||
“Commons Clause” License Condition v1.0
|
||||
|
||||
The Software is provided to you by the Licensor under the License, as defined below, subject to the following condition.
|
||||
|
||||
Without limiting other conditions in the License, the grant of rights under the License will not include, and the License does not grant to you, right to Sell the Software.
|
||||
|
||||
For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you under the License to provide to third parties, for a fee or other consideration (including without limitation fees for hosting or consulting/ support services related to the Software), a product or service whose value derives, entirely or substantially, from the functionality of the Software. Any license notice or attribution required by the License must also include this Commons Cause License Condition notice.
|
||||
|
||||
Software: shocknet api
|
||||
License: GPL3
|
||||
Licensor: Shock Network, Inc.
|
||||
|
||||
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 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 General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is 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. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
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.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
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 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. Use with the GNU Affero General Public License.
|
||||
|
||||
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 Affero 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 special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU 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 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 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 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 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU 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 the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
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 GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
<h1>Lightning.Pub</h1>
|
||||
# Awesome Project Build with TypeORM
|
||||
|
||||

|
||||
[](http://makeapullrequest.com)
|
||||
|
|
|
|||
|
|
@ -1,16 +0,0 @@
|
|||
version: "3.8"
|
||||
networks:
|
||||
default:
|
||||
external: true
|
||||
name: 2_default
|
||||
services:
|
||||
web:
|
||||
image: shockwallet/api:latest
|
||||
command: -c -h 0.0.0.0 -l polar-n2-alice:10009 -m /root/.lnd/data/chain/bitcoin/regtest/admin.macaroon -d /root/.lnd/tls.cert
|
||||
restart: on-failure
|
||||
stop_grace_period: 1m
|
||||
ports:
|
||||
- 9835:9835
|
||||
volumes:
|
||||
- C:\Users\boufn\.polar\networks\2\volumes\lnd\alice:/root/.lnd
|
||||
|
||||
|
|
@ -1,55 +0,0 @@
|
|||
const os = require("os");
|
||||
const path = require("path");
|
||||
const platform = os.platform();
|
||||
const homeDir = os.homedir();
|
||||
|
||||
const getLndDirectory = () => {
|
||||
if (platform === "darwin") {
|
||||
return homeDir + "/Library/Application Support/Lnd";
|
||||
} else if (platform === "win32") {
|
||||
// eslint-disable-next-line no-process-env
|
||||
const { APPDATA = "" } = process.env;
|
||||
return path.resolve(APPDATA, "../Local/Lnd");
|
||||
}
|
||||
|
||||
return homeDir + "/.lnd";
|
||||
};
|
||||
|
||||
const parsePath = (filePath = "") => {
|
||||
if (platform === "win32") {
|
||||
return filePath.replace("/", "\\");
|
||||
}
|
||||
|
||||
return filePath;
|
||||
};
|
||||
|
||||
const lndDirectory = getLndDirectory();
|
||||
|
||||
module.exports = (mainnet = false) => {
|
||||
const network = mainnet ? "mainnet" : "testnet";
|
||||
|
||||
return {
|
||||
serverPort: 9835,
|
||||
serverHost: "localhost",
|
||||
lndAddress: "127.0.0.1:9735",
|
||||
maxNumRoutesToQuery: 20,
|
||||
lndProto: parsePath(`${__dirname}/rpc.proto`),
|
||||
routerProto: parsePath(`${__dirname}/router.proto`),
|
||||
invoicesProto: parsePath(`${__dirname}/invoices.proto`),
|
||||
walletUnlockerProto: parsePath(`${__dirname}/walletunlocker.proto`),
|
||||
lndHost: "localhost:10009",
|
||||
lndCertPath: parsePath(`${lndDirectory}/tls.cert`),
|
||||
macaroonPath: parsePath(
|
||||
`${lndDirectory}/data/chain/bitcoin/${network}/admin.macaroon`
|
||||
),
|
||||
dataPath: parsePath(`${lndDirectory}/data`),
|
||||
loglevel: "info",
|
||||
logfile: "shockapi.log",
|
||||
lndLogFile: parsePath(`${lndDirectory}/logs/bitcoin/${network}/lnd.log`),
|
||||
lndDirPath: lndDirectory,
|
||||
peers: ['https://gun.shock.network/gun','https://gun-eu.shock.network/gun'],
|
||||
useTLS: false,
|
||||
tokenExpirationMS: 259200000,
|
||||
localtunnelHost:'https://tunnel.rip'
|
||||
};
|
||||
};
|
||||
|
|
@ -1,58 +0,0 @@
|
|||
/** @prettier */
|
||||
|
||||
const { createLogger, transports, format } = require('winston')
|
||||
const util = require('util')
|
||||
require('winston-daily-rotate-file')
|
||||
|
||||
// @ts-ignore
|
||||
const transform = info => {
|
||||
const args = info[Symbol.for('splat')]
|
||||
if (args) {
|
||||
return { ...info, message: util.format(info.message, ...args) }
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
const logFormatter = () => ({ transform })
|
||||
|
||||
const formatter = format.combine(
|
||||
format.colorize(),
|
||||
format.errors({ stack: true }),
|
||||
logFormatter(),
|
||||
format.prettyPrint(),
|
||||
format.timestamp(),
|
||||
format.simple(),
|
||||
format.align(),
|
||||
format.printf(info => {
|
||||
const { timestamp, level, message, stack, exception } = info
|
||||
|
||||
const ts = timestamp.slice(0, 19).replace('T', ' ')
|
||||
const isObject = typeof message === 'object'
|
||||
const formattedJson = isObject ? JSON.stringify(message, null, 2) : message
|
||||
const formattedException = exception ? exception.stack : ''
|
||||
const errorMessage = stack || formattedException
|
||||
const formattedMessage = errorMessage ? errorMessage : formattedJson
|
||||
|
||||
return `${ts} [${level}]: ${formattedMessage}`
|
||||
})
|
||||
)
|
||||
|
||||
const Logger = createLogger({
|
||||
format: formatter,
|
||||
transports: [
|
||||
new transports.DailyRotateFile({
|
||||
filename: 'shockapi.log',
|
||||
datePattern: 'yyyy-MM-DD',
|
||||
// https://github.com/winstonjs/winston-daily-rotate-file/issues/188
|
||||
json: false,
|
||||
maxSize: 1000000,
|
||||
maxFiles: 7,
|
||||
handleExceptions: true
|
||||
}),
|
||||
new transports.Console({
|
||||
handleExceptions: true
|
||||
})
|
||||
]
|
||||
})
|
||||
|
||||
module.exports = Logger
|
||||
|
|
@ -1,238 +0,0 @@
|
|||
syntax = "proto3";
|
||||
|
||||
import "rpc.proto";
|
||||
|
||||
package lnrpc;
|
||||
|
||||
option go_package = "github.com/lightningnetwork/lnd/lnrpc";
|
||||
|
||||
/*
|
||||
* Comments in this file will be directly parsed into the API
|
||||
* Documentation as descriptions of the associated method, message, or field.
|
||||
* These descriptions should go right above the definition of the object, and
|
||||
* can be in either block or // comment format.
|
||||
*
|
||||
* An RPC method can be matched to an lncli command by placing a line in the
|
||||
* beginning of the description in exactly the following format:
|
||||
* lncli: `methodname`
|
||||
*
|
||||
* Failure to specify the exact name of the command will cause documentation
|
||||
* generation to fail.
|
||||
*
|
||||
* More information on how exactly the gRPC documentation is generated from
|
||||
* this proto file can be found here:
|
||||
* https://github.com/lightninglabs/lightning-api
|
||||
*/
|
||||
|
||||
// WalletUnlocker is a service that is used to set up a wallet password for
|
||||
// lnd at first startup, and unlock a previously set up wallet.
|
||||
service WalletUnlocker {
|
||||
/*
|
||||
GenSeed is the first method that should be used to instantiate a new lnd
|
||||
instance. This method allows a caller to generate a new aezeed cipher seed
|
||||
given an optional passphrase. If provided, the passphrase will be necessary
|
||||
to decrypt the cipherseed to expose the internal wallet seed.
|
||||
|
||||
Once the cipherseed is obtained and verified by the user, the InitWallet
|
||||
method should be used to commit the newly generated seed, and create the
|
||||
wallet.
|
||||
*/
|
||||
rpc GenSeed (GenSeedRequest) returns (GenSeedResponse);
|
||||
|
||||
/*
|
||||
InitWallet is used when lnd is starting up for the first time to fully
|
||||
initialize the daemon and its internal wallet. At the very least a wallet
|
||||
password must be provided. This will be used to encrypt sensitive material
|
||||
on disk.
|
||||
|
||||
In the case of a recovery scenario, the user can also specify their aezeed
|
||||
mnemonic and passphrase. If set, then the daemon will use this prior state
|
||||
to initialize its internal wallet.
|
||||
|
||||
Alternatively, this can be used along with the GenSeed RPC to obtain a
|
||||
seed, then present it to the user. Once it has been verified by the user,
|
||||
the seed can be fed into this RPC in order to commit the new wallet.
|
||||
*/
|
||||
rpc InitWallet (InitWalletRequest) returns (InitWalletResponse);
|
||||
|
||||
/* lncli: `unlock`
|
||||
UnlockWallet is used at startup of lnd to provide a password to unlock
|
||||
the wallet database.
|
||||
*/
|
||||
rpc UnlockWallet (UnlockWalletRequest) returns (UnlockWalletResponse);
|
||||
|
||||
/* lncli: `changepassword`
|
||||
ChangePassword changes the password of the encrypted wallet. This will
|
||||
automatically unlock the wallet database if successful.
|
||||
*/
|
||||
rpc ChangePassword (ChangePasswordRequest) returns (ChangePasswordResponse);
|
||||
}
|
||||
|
||||
message GenSeedRequest {
|
||||
/*
|
||||
aezeed_passphrase is an optional user provided passphrase that will be used
|
||||
to encrypt the generated aezeed cipher seed. When using REST, this field
|
||||
must be encoded as base64.
|
||||
*/
|
||||
bytes aezeed_passphrase = 1;
|
||||
|
||||
/*
|
||||
seed_entropy is an optional 16-bytes generated via CSPRNG. If not
|
||||
specified, then a fresh set of randomness will be used to create the seed.
|
||||
When using REST, this field must be encoded as base64.
|
||||
*/
|
||||
bytes seed_entropy = 2;
|
||||
}
|
||||
message GenSeedResponse {
|
||||
/*
|
||||
cipher_seed_mnemonic is a 24-word mnemonic that encodes a prior aezeed
|
||||
cipher seed obtained by the user. This field is optional, as if not
|
||||
provided, then the daemon will generate a new cipher seed for the user.
|
||||
Otherwise, then the daemon will attempt to recover the wallet state linked
|
||||
to this cipher seed.
|
||||
*/
|
||||
repeated string cipher_seed_mnemonic = 1;
|
||||
|
||||
/*
|
||||
enciphered_seed are the raw aezeed cipher seed bytes. This is the raw
|
||||
cipher text before run through our mnemonic encoding scheme.
|
||||
*/
|
||||
bytes enciphered_seed = 2;
|
||||
}
|
||||
|
||||
message InitWalletRequest {
|
||||
/*
|
||||
wallet_password is the passphrase that should be used to encrypt the
|
||||
wallet. This MUST be at least 8 chars in length. After creation, this
|
||||
password is required to unlock the daemon. When using REST, this field
|
||||
must be encoded as base64.
|
||||
*/
|
||||
bytes wallet_password = 1;
|
||||
|
||||
/*
|
||||
cipher_seed_mnemonic is a 24-word mnemonic that encodes a prior aezeed
|
||||
cipher seed obtained by the user. This may have been generated by the
|
||||
GenSeed method, or be an existing seed.
|
||||
*/
|
||||
repeated string cipher_seed_mnemonic = 2;
|
||||
|
||||
/*
|
||||
aezeed_passphrase is an optional user provided passphrase that will be used
|
||||
to encrypt the generated aezeed cipher seed. When using REST, this field
|
||||
must be encoded as base64.
|
||||
*/
|
||||
bytes aezeed_passphrase = 3;
|
||||
|
||||
/*
|
||||
recovery_window is an optional argument specifying the address lookahead
|
||||
when restoring a wallet seed. The recovery window applies to each
|
||||
individual branch of the BIP44 derivation paths. Supplying a recovery
|
||||
window of zero indicates that no addresses should be recovered, such after
|
||||
the first initialization of the wallet.
|
||||
*/
|
||||
int32 recovery_window = 4;
|
||||
|
||||
/*
|
||||
channel_backups is an optional argument that allows clients to recover the
|
||||
settled funds within a set of channels. This should be populated if the
|
||||
user was unable to close out all channels and sweep funds before partial or
|
||||
total data loss occurred. If specified, then after on-chain recovery of
|
||||
funds, lnd begin to carry out the data loss recovery protocol in order to
|
||||
recover the funds in each channel from a remote force closed transaction.
|
||||
*/
|
||||
ChanBackupSnapshot channel_backups = 5;
|
||||
|
||||
/*
|
||||
stateless_init is an optional argument instructing the daemon NOT to create
|
||||
any *.macaroon files in its filesystem. If this parameter is set, then the
|
||||
admin macaroon returned in the response MUST be stored by the caller of the
|
||||
RPC as otherwise all access to the daemon will be lost!
|
||||
*/
|
||||
bool stateless_init = 6;
|
||||
}
|
||||
message InitWalletResponse {
|
||||
/*
|
||||
The binary serialized admin macaroon that can be used to access the daemon
|
||||
after creating the wallet. If the stateless_init parameter was set to true,
|
||||
this is the ONLY copy of the macaroon and MUST be stored safely by the
|
||||
caller. Otherwise a copy of this macaroon is also persisted on disk by the
|
||||
daemon, together with other macaroon files.
|
||||
*/
|
||||
bytes admin_macaroon = 1;
|
||||
}
|
||||
|
||||
message UnlockWalletRequest {
|
||||
/*
|
||||
wallet_password should be the current valid passphrase for the daemon. This
|
||||
will be required to decrypt on-disk material that the daemon requires to
|
||||
function properly. When using REST, this field must be encoded as base64.
|
||||
*/
|
||||
bytes wallet_password = 1;
|
||||
|
||||
/*
|
||||
recovery_window is an optional argument specifying the address lookahead
|
||||
when restoring a wallet seed. The recovery window applies to each
|
||||
individual branch of the BIP44 derivation paths. Supplying a recovery
|
||||
window of zero indicates that no addresses should be recovered, such after
|
||||
the first initialization of the wallet.
|
||||
*/
|
||||
int32 recovery_window = 2;
|
||||
|
||||
/*
|
||||
channel_backups is an optional argument that allows clients to recover the
|
||||
settled funds within a set of channels. This should be populated if the
|
||||
user was unable to close out all channels and sweep funds before partial or
|
||||
total data loss occurred. If specified, then after on-chain recovery of
|
||||
funds, lnd begin to carry out the data loss recovery protocol in order to
|
||||
recover the funds in each channel from a remote force closed transaction.
|
||||
*/
|
||||
ChanBackupSnapshot channel_backups = 3;
|
||||
|
||||
/*
|
||||
stateless_init is an optional argument instructing the daemon NOT to create
|
||||
any *.macaroon files in its file system.
|
||||
*/
|
||||
bool stateless_init = 4;
|
||||
}
|
||||
message UnlockWalletResponse {
|
||||
}
|
||||
|
||||
message ChangePasswordRequest {
|
||||
/*
|
||||
current_password should be the current valid passphrase used to unlock the
|
||||
daemon. When using REST, this field must be encoded as base64.
|
||||
*/
|
||||
bytes current_password = 1;
|
||||
|
||||
/*
|
||||
new_password should be the new passphrase that will be needed to unlock the
|
||||
daemon. When using REST, this field must be encoded as base64.
|
||||
*/
|
||||
bytes new_password = 2;
|
||||
|
||||
/*
|
||||
stateless_init is an optional argument instructing the daemon NOT to create
|
||||
any *.macaroon files in its filesystem. If this parameter is set, then the
|
||||
admin macaroon returned in the response MUST be stored by the caller of the
|
||||
RPC as otherwise all access to the daemon will be lost!
|
||||
*/
|
||||
bool stateless_init = 3;
|
||||
|
||||
/*
|
||||
new_macaroon_root_key is an optional argument instructing the daemon to
|
||||
rotate the macaroon root key when set to true. This will invalidate all
|
||||
previously generated macaroons.
|
||||
*/
|
||||
bool new_macaroon_root_key = 4;
|
||||
}
|
||||
message ChangePasswordResponse {
|
||||
/*
|
||||
The binary serialized admin macaroon that can be used to access the daemon
|
||||
after rotating the macaroon root key. If both the stateless_init and
|
||||
new_macaroon_root_key parameter were set to true, this is the ONLY copy of
|
||||
the macaroon that was created from the new root key and MUST be stored
|
||||
safely by the caller. Otherwise a copy of this macaroon is also persisted on
|
||||
disk by the daemon, together with other macaroon files.
|
||||
*/
|
||||
bytes admin_macaroon = 1;
|
||||
}
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
module.exports = {
|
||||
/**
|
||||
* @param {string} path
|
||||
*/
|
||||
MACAROON_PATH: path => `
|
||||
The specified macaroon path "${path}" was not found.
|
||||
This issue can be caused by:
|
||||
|
||||
1. Setting an invalid path for your Macaroon file.
|
||||
2. Not initializing your wallet before using the ShockAPI
|
||||
`,
|
||||
/**
|
||||
* @param {string} path
|
||||
*/
|
||||
CERT_PATH: path => `
|
||||
The specified LND certificate file "${path}" was not found.
|
||||
This issue can be caused by:
|
||||
|
||||
1. Setting an invalid path for your Certificates.
|
||||
2. Not initializing your wallet before using the ShockAPI
|
||||
`,
|
||||
CERT_MISSING: () =>
|
||||
"Required LND certificate path missing from application configuration.",
|
||||
/**
|
||||
* @param {string|null} macaroonPath
|
||||
* @param {string} lndCertPath
|
||||
*/
|
||||
CERT_AND_MACAROON_MISSING: (macaroonPath, lndCertPath) =>
|
||||
`
|
||||
You neither specified an LND cert path nor a Macaroon path. Please make sure both files exist in the paths you've specified:
|
||||
|
||||
Macaroon Path: ${macaroonPath ? macaroonPath : "N/A"}
|
||||
LND Certificates path: ${lndCertPath ? lndCertPath : "N/A"}
|
||||
`
|
||||
};
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
#!/bin/ash
|
||||
node main -h 0.0.0.0 \
|
||||
-m admin.macaroon \
|
||||
-d tls.cert \
|
||||
-l $LND_ADDR
|
||||
5
example.env
Normal file
5
example.env
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
LND_ADDRESS=
|
||||
LND_CERT_PATH=
|
||||
LND_MACAROON_PATH=
|
||||
DATABASE_FILE=db.sqlite
|
||||
JWT_SECRET=bigsecrethere
|
||||
78
guntest.html
78
guntest.html
|
|
@ -1,78 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="X-UA-Compatible" content="ie=edge">
|
||||
<title>Document</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
</body>
|
||||
<script src="node_modules/gun/gun.js"></script>
|
||||
<script src="node_modules/gun/sea.js"></script>
|
||||
<script src="node_modules/gun/lib/open.js"></script>
|
||||
<script src="node_modules/gun/lib/open.js"></script>
|
||||
<script src="node_modules/gun/lib/load.js"></script>
|
||||
<script src="node_modules/gun/lib/unset.js"></script>
|
||||
<script src="node_modules/gun/lib/promise.js"></script>
|
||||
<script src="node_modules/gun/lib/then.js"></script>
|
||||
<script src="node_modules/gun/nts.js"></script>
|
||||
<script>
|
||||
|
||||
gun = Gun({
|
||||
peers: ['https://gun.shock.network/gun','https://gun-eu.shock.network/gun'],
|
||||
axe: false
|
||||
})
|
||||
|
||||
setInterval(() => {
|
||||
console.log('peers', Object.keys(gun.back('opt').peers))
|
||||
},5000)
|
||||
|
||||
user = gun.user()
|
||||
|
||||
node = gun.get('foo').get('bar')
|
||||
|
||||
capdog = gun.user('qsgziGQS99sPUxV1CRwwRckn9cG6cJ3prbDsrbL7qko.oRbCaVKwJFQURWrS1pFhkfAzrkEvkQgBRIUz9uoWtrg')
|
||||
explorador = gun.user(`zBQkPb1ohbdjVp_29TKFXyv_0g3amKgRJRqKr0E-Oyk.yB1P4UmOrzkGuPEL5zUgLETJWyYpM9K3l2ycNlt8jiY`)
|
||||
pleb = gun.user(`e1C60yZ1Cm3Mkceq7L9SmH6QQ7zsDdbibPFeQz7tNsk._1VlqJNo8BIJmzz2D5WELiMiRjBh3DBlDvzC6fNltZw`)
|
||||
boblazar = gun.user(`g6fcZ_1zyFwV1jR1eNK1GTUr2sSlEDL1D5vBsSvKoKg.2OA9MQHO2c1wjv6L-VPBFf36EZXjgQ1nnZFbOE9_5-o`)
|
||||
|
||||
const UPPER = 100
|
||||
|
||||
clearSet = (node) => {
|
||||
node.once((map) => {
|
||||
Object.keys(map).forEach(key => node.get(key).put(null))
|
||||
}, { wait: 1500 })
|
||||
}
|
||||
|
||||
put = async () => {
|
||||
const res = await fetch(`https://jsonplaceholder.typicode.com/posts`)
|
||||
/** @type {Array<any>} */
|
||||
const data = await res.json()
|
||||
|
||||
const obj = {}
|
||||
|
||||
data.slice(0, UPPER).forEach((v, i) => obj[i] = v)
|
||||
|
||||
node.put(obj, ack => {
|
||||
console.log(ack.err ? `err: ${ack.err}` : 'ok')
|
||||
})
|
||||
}
|
||||
|
||||
erase = () => {
|
||||
(new Array(UPPER)).fill(null).map((_, i) => i).forEach(n => {
|
||||
node.get(n).put(null, ack => {
|
||||
console.log(ack.err ? `err: ${ack.err}` : 'ok')
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
</script>
|
||||
<style>
|
||||
|
||||
body {
|
||||
background-color: black;
|
||||
}
|
||||
</style>
|
||||
</html>
|
||||
27
main.js
27
main.js
|
|
@ -1,27 +0,0 @@
|
|||
const program = require("commander");
|
||||
|
||||
const {version} = (JSON.parse(require('fs').readFileSync("./package.json", "utf-8")))
|
||||
|
||||
// parse command line parameters
|
||||
program
|
||||
.version(version)
|
||||
.option("-s, --serverport [port]", "web server http listening port (defaults to 9835)")
|
||||
.option("-h, --serverhost [host]", "web server listening host (defaults to localhost)")
|
||||
.option("-l, --lndhost [host:port]", "RPC lnd host (defaults to localhost:10009)")
|
||||
.option("-u, --user [login]", "basic authentication login")
|
||||
.option("-p, --pwd [password]", "basic authentication password")
|
||||
.option("-m, --macaroon-path [file path]", "path to admin.macaroon file")
|
||||
.option("-d, --lnd-cert-path [file path]", "path to LND cert file")
|
||||
.option("-f, --logfile [file path]", "path to file where to store the application logs")
|
||||
.option("-e, --loglevel [level]", "level of logs to display (debug, info, warn, error)")
|
||||
.option("-k, --le-email [email]", "lets encrypt required contact email")
|
||||
.option("-c, --mainnet", "run server on mainnet mode")
|
||||
.option("-t, --tunnel","create a localtunnel to listen behind a firewall")
|
||||
.option('-r, --lndaddress', 'Lnd address, defaults to 127.0.0.1:9735')
|
||||
.option('-a, --use-TLS', 'use TLS')
|
||||
.option('-i, --https-cert [path]', 'HTTPS certificate path')
|
||||
.option('-y, --https-cert-key [path]', 'HTTPS certificate key path')
|
||||
.parse(process.argv);
|
||||
|
||||
// load server
|
||||
require("./src/server")(program); // Standard server version
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
{
|
||||
"watch": ["src/", "services/", "utils/", "constants/", "config/"],
|
||||
"ignore": ["node_modules/", ".git", "radata/", ".storage/", "*.log.*"],
|
||||
"verbose": true,
|
||||
"ext": "js"
|
||||
}
|
||||
6736
package-lock.json
generated
Normal file
6736
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
153
package.json
153
package.json
|
|
@ -1,113 +1,64 @@
|
|||
{
|
||||
"name": "lightningpub",
|
||||
"version": "2022.12.1",
|
||||
"name": "lightning.pub",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "src/server.js",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"start": "node main.js -c",
|
||||
"dev": "node --trace-warnings --max-old-space-size=4096 main.js -h 0.0.0.0",
|
||||
"dev:watch": "nodemon main.js -- -h 0.0.0.0",
|
||||
"dev:attach": "node --inspect --trace-warnings --max-old-space-size=4096 main.js -h 0.0.0.0",
|
||||
"test": "mocha ./utils -b -t 50000 --recursive",
|
||||
"typecheck": "tsc",
|
||||
"lint": "eslint \"services/gunDB/**/*.js\"",
|
||||
"format": "prettier --write \"./**/*.js\"",
|
||||
"test": "tsc && testyts",
|
||||
"start": "ts-node src/index.ts",
|
||||
"build_autogenerated": "cd proto && rimraf autogenerated && protoc -I ./service --pub_out=. service/*",
|
||||
"build_lnd_client_1": "cd proto && protoc -I ./others --plugin=.\\node_modules\\.bin\\protoc-gen-ts_proto.cmd --ts_proto_out=./lnd --ts_proto_opt=esModuleInterop=true others/* ",
|
||||
"build_lnd_client": "cd proto && rimraf lnd/* && npx protoc --ts_out ./lnd --ts_opt long_type_string --proto_path others others/* ",
|
||||
"typeorm": "typeorm-ts-node-commonjs"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/shocknet/Lightning.Pub.git"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"bugs": {
|
||||
"url": "https://github.com/shocknet/Lightning.Pub/issues"
|
||||
},
|
||||
"homepage": "https://github.com/shocknet/Lightning.Pub#readme",
|
||||
"dependencies": {
|
||||
"@grpc/grpc-js": "^1.2.2",
|
||||
"@grpc/proto-loader": "^0.5.5",
|
||||
"assert-never": "^1.2.1",
|
||||
"axios": "^1.1.2",
|
||||
"basic-auth": "^2.0.0",
|
||||
"big.js": "^6.2.1",
|
||||
"bitcore-lib": "^8.25.8",
|
||||
"bluebird": "^3.7.2",
|
||||
"body-parser": "^1.16.0",
|
||||
"colors": "^1.4.0",
|
||||
"command-exists": "^1.2.6",
|
||||
"commander": "^9.4.1",
|
||||
"compression": "^1.7.4",
|
||||
"@grpc/grpc-js": "^1.6.7",
|
||||
"@protobuf-ts/grpc-transport": "^2.5.0",
|
||||
"@protobuf-ts/plugin": "^2.5.0",
|
||||
"@protobuf-ts/runtime": "^2.5.0",
|
||||
"@types/express": "^4.17.13",
|
||||
"@types/node": "^17.0.31",
|
||||
"@types/secp256k1": "^4.0.3",
|
||||
"axios": "^0.27.2",
|
||||
"copyfiles": "^2.4.1",
|
||||
"cors": "^2.8.5",
|
||||
"debug": "^3.1.0",
|
||||
"dotenv": "^16.0.3",
|
||||
"dotenv": "^16.0.0",
|
||||
"eccrypto": "^1.1.6",
|
||||
"express": "^4.14.1",
|
||||
"express-session": "^1.17.1",
|
||||
"google-proto-files": "^1.0.3",
|
||||
"graphviz": "0.0.9",
|
||||
"grpc": "1.24.4",
|
||||
"husky": "^8.0.1",
|
||||
"jsonfile": "^6.1.0",
|
||||
"jsonwebtoken": "^8.3.0",
|
||||
"express": "^4.18.1",
|
||||
"grpc-tools": "^1.11.2",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
"lodash": "^4.17.21",
|
||||
"method-override": "^3.0.0",
|
||||
"node-fetch": "^3.2.10",
|
||||
"node-persist": "^3.1.0",
|
||||
"promise": "^8.1.0",
|
||||
"qrcode-terminal": "^0.12.0",
|
||||
"ramda": "^0.27.1",
|
||||
"request": "^2.88.2",
|
||||
"request-promise": "^4.2.6",
|
||||
"response-time": "^2.3.2",
|
||||
"shelljs": "^0.8.2",
|
||||
"shock-common": "^37.0.0",
|
||||
"socket.io": "4.0.1",
|
||||
"socket.io-msgpack-parser": "^3.0.1",
|
||||
"text-encoding": "^0.7.0",
|
||||
"tingodb": "^0.6.1",
|
||||
"uuid": "3.x.x",
|
||||
"winston": "^3.3.3",
|
||||
"winston-daily-rotate-file": "^4.5.0"
|
||||
"pg": "^8.4.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"rxjs": "^7.5.5",
|
||||
"secp256k1": "^4.0.3",
|
||||
"sqlite3": "^5.1.2",
|
||||
"ts-node": "^10.7.0",
|
||||
"ts-proto": "^1.112.1",
|
||||
"typeorm": "0.3.10",
|
||||
"typescript": "^4.6.4",
|
||||
"uuid": "^8.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/plugin-proposal-class-properties": "^7.12.1",
|
||||
"@types/bluebird": "^3.5.32",
|
||||
"@types/dotenv": "^8.2.0",
|
||||
"@types/eccrypto": "^1.1.2",
|
||||
"@types/express": "^4.17.1",
|
||||
"@types/gun": "^0.9.2",
|
||||
"@types/jsonwebtoken": "^8.3.7",
|
||||
"@types/lodash": "^4.14.168",
|
||||
"@types/mocha": "^9.0.0",
|
||||
"@types/node-fetch": "^2.5.8",
|
||||
"@types/node-persist": "^3.1.1",
|
||||
"@types/ramda": "types/npm-ramda#dist",
|
||||
"@types/random-words": "^1.1.2",
|
||||
"@types/react": "16.x.x",
|
||||
"@types/uuid": "^8.3.0",
|
||||
"babel-eslint": "^10.1.0",
|
||||
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
|
||||
"eslint": "^8.25.0",
|
||||
"eslint-config-prettier": "^6.5.0",
|
||||
"eslint-plugin-babel": "^5.3.1",
|
||||
"eslint-plugin-jest": "^22.20.1",
|
||||
"eslint-plugin-prettier": "^3.4.0",
|
||||
"jest": "^24.9.0",
|
||||
"lint-staged": "^10.5.4",
|
||||
"nodemon": "^2.0.7",
|
||||
"prettier": "^1.18.2",
|
||||
"random-words": "^1.1.1",
|
||||
"rimraf": "^3.0.2",
|
||||
"ts-node": "^9.1.1",
|
||||
"ts-type": "^3.0.1",
|
||||
"typescript": "^4.5.4"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.js": [
|
||||
"prettier --check",
|
||||
"eslint"
|
||||
],
|
||||
"*.ts": [
|
||||
"prettier --check"
|
||||
]
|
||||
},
|
||||
"husky": {
|
||||
"hooks": {}
|
||||
},
|
||||
"engines": {
|
||||
"npm": "Use yarn!"
|
||||
},
|
||||
"packageManager": "yarn@3.1.1"
|
||||
}
|
||||
"@types/cors": "^2.8.12",
|
||||
"@types/eccrypto": "^1.1.3",
|
||||
"@types/jsonwebtoken": "^8.5.9",
|
||||
"@types/lodash": "^4.14.182",
|
||||
"@types/node": "^16.11.10",
|
||||
"@types/uuid": "^8.3.4",
|
||||
"testyts": "^1.5.0",
|
||||
"ts-node": "10.7.0",
|
||||
"typescript": "4.5.2"
|
||||
}
|
||||
}
|
||||
2
proto/CODEGEN.md
Normal file
2
proto/CODEGEN.md
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
create lnd classes: `npx protoc -I ./others --ts_out=./lnd others/*`
|
||||
create server classes: `npx protoc -I ./service --pub_out=. service/*`
|
||||
697
proto/autogenerated/debug.txt
Normal file
697
proto/autogenerated/debug.txt
Normal file
|
|
@ -0,0 +1,697 @@
|
|||
([]*main.Method) (len=11 cap=16) {
|
||||
(*main.Method)(0xc0002886e0)({
|
||||
in: (main.MethodMessage) {
|
||||
name: (string) (len=5) "Empty",
|
||||
hasZeroFields: (bool) true
|
||||
},
|
||||
name: (string) (len=6) "Health",
|
||||
out: (main.MethodMessage) {
|
||||
name: (string) (len=5) "Empty",
|
||||
hasZeroFields: (bool) true
|
||||
},
|
||||
opts: (*main.methodOptions)(0xc0003cc420)({
|
||||
authType: (*main.supportedAuth)(0xc000379fb0)({
|
||||
id: (string) (len=5) "guest",
|
||||
name: (string) (len=5) "Guest",
|
||||
encrypted: (bool) false,
|
||||
context: (map[string]string) {
|
||||
}
|
||||
}),
|
||||
method: (string) (len=3) "get",
|
||||
route: (main.decodedRoute) {
|
||||
route: (string) (len=11) "/api/health",
|
||||
params: ([]string) <nil>
|
||||
},
|
||||
query: ([]string) <nil>
|
||||
})
|
||||
}),
|
||||
(*main.Method)(0xc000288730)({
|
||||
in: (main.MethodMessage) {
|
||||
name: (string) (len=25) "EncryptionExchangeRequest",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
name: (string) (len=18) "EncryptionExchange",
|
||||
out: (main.MethodMessage) {
|
||||
name: (string) (len=5) "Empty",
|
||||
hasZeroFields: (bool) true
|
||||
},
|
||||
opts: (*main.methodOptions)(0xc0003cc5a0)({
|
||||
authType: (*main.supportedAuth)(0xc0003d60c0)({
|
||||
id: (string) (len=5) "guest",
|
||||
name: (string) (len=5) "Guest",
|
||||
encrypted: (bool) false,
|
||||
context: (map[string]string) {
|
||||
}
|
||||
}),
|
||||
method: (string) (len=4) "post",
|
||||
route: (main.decodedRoute) {
|
||||
route: (string) (len=24) "/api/encryption/exchange",
|
||||
params: ([]string) <nil>
|
||||
},
|
||||
query: ([]string) <nil>
|
||||
})
|
||||
}),
|
||||
(*main.Method)(0xc000288780)({
|
||||
in: (main.MethodMessage) {
|
||||
name: (string) (len=17) "LndGetInfoRequest",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
name: (string) (len=10) "LndGetInfo",
|
||||
out: (main.MethodMessage) {
|
||||
name: (string) (len=18) "LndGetInfoResponse",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
opts: (*main.methodOptions)(0xc0003cc720)({
|
||||
authType: (*main.supportedAuth)(0xc0003d6180)({
|
||||
id: (string) (len=5) "admin",
|
||||
name: (string) (len=5) "Admin",
|
||||
encrypted: (bool) true,
|
||||
context: (map[string]string) (len=1) {
|
||||
(string) (len=8) "admin_id": (string) (len=6) "string"
|
||||
}
|
||||
}),
|
||||
method: (string) (len=4) "post",
|
||||
route: (main.decodedRoute) {
|
||||
route: (string) (len=16) "/api/lnd/getinfo",
|
||||
params: ([]string) <nil>
|
||||
},
|
||||
query: ([]string) <nil>
|
||||
})
|
||||
}),
|
||||
(*main.Method)(0xc0002887d0)({
|
||||
in: (main.MethodMessage) {
|
||||
name: (string) (len=14) "AddUserRequest",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
name: (string) (len=7) "AddUser",
|
||||
out: (main.MethodMessage) {
|
||||
name: (string) (len=15) "AddUserResponse",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
opts: (*main.methodOptions)(0xc0003cc8a0)({
|
||||
authType: (*main.supportedAuth)(0xc0003d6240)({
|
||||
id: (string) (len=5) "guest",
|
||||
name: (string) (len=5) "Guest",
|
||||
encrypted: (bool) false,
|
||||
context: (map[string]string) {
|
||||
}
|
||||
}),
|
||||
method: (string) (len=4) "post",
|
||||
route: (main.decodedRoute) {
|
||||
route: (string) (len=13) "/api/user/add",
|
||||
params: ([]string) <nil>
|
||||
},
|
||||
query: ([]string) <nil>
|
||||
})
|
||||
}),
|
||||
(*main.Method)(0xc000288820)({
|
||||
in: (main.MethodMessage) {
|
||||
name: (string) (len=15) "AuthUserRequest",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
name: (string) (len=8) "AuthUser",
|
||||
out: (main.MethodMessage) {
|
||||
name: (string) (len=16) "AuthUserResponse",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
opts: (*main.methodOptions)(0xc0003cca20)({
|
||||
authType: (*main.supportedAuth)(0xc0003d6300)({
|
||||
id: (string) (len=5) "guest",
|
||||
name: (string) (len=5) "Guest",
|
||||
encrypted: (bool) false,
|
||||
context: (map[string]string) {
|
||||
}
|
||||
}),
|
||||
method: (string) (len=4) "post",
|
||||
route: (main.decodedRoute) {
|
||||
route: (string) (len=14) "/api/user/auth",
|
||||
params: ([]string) <nil>
|
||||
},
|
||||
query: ([]string) <nil>
|
||||
})
|
||||
}),
|
||||
(*main.Method)(0xc0002888c0)({
|
||||
in: (main.MethodMessage) {
|
||||
name: (string) (len=17) "NewAddressRequest",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
name: (string) (len=10) "NewAddress",
|
||||
out: (main.MethodMessage) {
|
||||
name: (string) (len=18) "NewAddressResponse",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
opts: (*main.methodOptions)(0xc0003ccba0)({
|
||||
authType: (*main.supportedAuth)(0xc0003d63c0)({
|
||||
id: (string) (len=4) "user",
|
||||
name: (string) (len=4) "User",
|
||||
encrypted: (bool) false,
|
||||
context: (map[string]string) (len=1) {
|
||||
(string) (len=7) "user_id": (string) (len=6) "string"
|
||||
}
|
||||
}),
|
||||
method: (string) (len=4) "post",
|
||||
route: (main.decodedRoute) {
|
||||
route: (string) (len=19) "/api/user/chain/new",
|
||||
params: ([]string) <nil>
|
||||
},
|
||||
query: ([]string) <nil>
|
||||
})
|
||||
}),
|
||||
(*main.Method)(0xc000288960)({
|
||||
in: (main.MethodMessage) {
|
||||
name: (string) (len=17) "PayAddressRequest",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
name: (string) (len=10) "PayAddress",
|
||||
out: (main.MethodMessage) {
|
||||
name: (string) (len=18) "PayAddressResponse",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
opts: (*main.methodOptions)(0xc0003ccd20)({
|
||||
authType: (*main.supportedAuth)(0xc0003d6480)({
|
||||
id: (string) (len=4) "user",
|
||||
name: (string) (len=4) "User",
|
||||
encrypted: (bool) false,
|
||||
context: (map[string]string) (len=1) {
|
||||
(string) (len=7) "user_id": (string) (len=6) "string"
|
||||
}
|
||||
}),
|
||||
method: (string) (len=4) "post",
|
||||
route: (main.decodedRoute) {
|
||||
route: (string) (len=19) "/api/user/chain/pay",
|
||||
params: ([]string) <nil>
|
||||
},
|
||||
query: ([]string) <nil>
|
||||
})
|
||||
}),
|
||||
(*main.Method)(0xc000288a00)({
|
||||
in: (main.MethodMessage) {
|
||||
name: (string) (len=17) "NewInvoiceRequest",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
name: (string) (len=10) "NewInvoice",
|
||||
out: (main.MethodMessage) {
|
||||
name: (string) (len=18) "NewInvoiceResponse",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
opts: (*main.methodOptions)(0xc0003ccea0)({
|
||||
authType: (*main.supportedAuth)(0xc0003d6540)({
|
||||
id: (string) (len=4) "user",
|
||||
name: (string) (len=4) "User",
|
||||
encrypted: (bool) false,
|
||||
context: (map[string]string) (len=1) {
|
||||
(string) (len=7) "user_id": (string) (len=6) "string"
|
||||
}
|
||||
}),
|
||||
method: (string) (len=4) "post",
|
||||
route: (main.decodedRoute) {
|
||||
route: (string) (len=21) "/api/user/invoice/new",
|
||||
params: ([]string) <nil>
|
||||
},
|
||||
query: ([]string) <nil>
|
||||
})
|
||||
}),
|
||||
(*main.Method)(0xc000288aa0)({
|
||||
in: (main.MethodMessage) {
|
||||
name: (string) (len=17) "PayInvoiceRequest",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
name: (string) (len=10) "PayInvoice",
|
||||
out: (main.MethodMessage) {
|
||||
name: (string) (len=18) "PayInvoiceResponse",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
opts: (*main.methodOptions)(0xc0003cd020)({
|
||||
authType: (*main.supportedAuth)(0xc0003d6600)({
|
||||
id: (string) (len=4) "user",
|
||||
name: (string) (len=4) "User",
|
||||
encrypted: (bool) false,
|
||||
context: (map[string]string) (len=1) {
|
||||
(string) (len=7) "user_id": (string) (len=6) "string"
|
||||
}
|
||||
}),
|
||||
method: (string) (len=4) "post",
|
||||
route: (main.decodedRoute) {
|
||||
route: (string) (len=21) "/api/user/invoice/pay",
|
||||
params: ([]string) <nil>
|
||||
},
|
||||
query: ([]string) <nil>
|
||||
})
|
||||
}),
|
||||
(*main.Method)(0xc000288b40)({
|
||||
in: (main.MethodMessage) {
|
||||
name: (string) (len=18) "OpenChannelRequest",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
name: (string) (len=11) "OpenChannel",
|
||||
out: (main.MethodMessage) {
|
||||
name: (string) (len=19) "OpenChannelResponse",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
opts: (*main.methodOptions)(0xc0003cd1a0)({
|
||||
authType: (*main.supportedAuth)(0xc0003d66c0)({
|
||||
id: (string) (len=4) "user",
|
||||
name: (string) (len=4) "User",
|
||||
encrypted: (bool) false,
|
||||
context: (map[string]string) (len=1) {
|
||||
(string) (len=7) "user_id": (string) (len=6) "string"
|
||||
}
|
||||
}),
|
||||
method: (string) (len=4) "post",
|
||||
route: (main.decodedRoute) {
|
||||
route: (string) (len=22) "/api/user/open/channel",
|
||||
params: ([]string) <nil>
|
||||
},
|
||||
query: ([]string) <nil>
|
||||
})
|
||||
}),
|
||||
(*main.Method)(0xc000288b90)({
|
||||
in: (main.MethodMessage) {
|
||||
name: (string) (len=5) "Empty",
|
||||
hasZeroFields: (bool) true
|
||||
},
|
||||
name: (string) (len=19) "GetOpenChannelLNURL",
|
||||
out: (main.MethodMessage) {
|
||||
name: (string) (len=27) "GetOpenChannelLNURLResponse",
|
||||
hasZeroFields: (bool) false
|
||||
},
|
||||
opts: (*main.methodOptions)(0xc0003cd320)({
|
||||
authType: (*main.supportedAuth)(0xc0003d6780)({
|
||||
id: (string) (len=4) "user",
|
||||
name: (string) (len=4) "User",
|
||||
encrypted: (bool) false,
|
||||
context: (map[string]string) (len=1) {
|
||||
(string) (len=7) "user_id": (string) (len=6) "string"
|
||||
}
|
||||
}),
|
||||
method: (string) (len=4) "post",
|
||||
route: (main.decodedRoute) {
|
||||
route: (string) (len=23) "/api/user/lnurl_channel",
|
||||
params: ([]string) <nil>
|
||||
},
|
||||
query: ([]string) <nil>
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
([]*main.Enum) (len=1 cap=1) {
|
||||
(*main.Enum)(0xc000379860)({
|
||||
name: (string) (len=11) "AddressType",
|
||||
values: ([]main.EnumValue) (len=3 cap=4) {
|
||||
(main.EnumValue) {
|
||||
number: (int64) 0,
|
||||
name: (string) (len=19) "WITNESS_PUBKEY_HASH"
|
||||
},
|
||||
(main.EnumValue) {
|
||||
number: (int64) 1,
|
||||
name: (string) (len=18) "NESTED_PUBKEY_HASH"
|
||||
},
|
||||
(main.EnumValue) {
|
||||
number: (int64) 2,
|
||||
name: (string) (len=14) "TAPROOT_PUBKEY"
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
(map[string]*main.Message) (len=19) {
|
||||
(string) (len=17) "LndGetInfoRequest": (*main.Message)(0xc000215140)({
|
||||
fullName: (string) (len=17) "LndGetInfoRequest",
|
||||
name: (string) (len=17) "LndGetInfoRequest",
|
||||
fields: ([]*main.Field) (len=1 cap=1) {
|
||||
(*main.Field)(0xc000379320)({
|
||||
name: (string) (len=7) "node_id",
|
||||
kind: (string) (len=5) "int64",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
}),
|
||||
(string) (len=18) "LndGetInfoResponse": (*main.Message)(0xc000215180)({
|
||||
fullName: (string) (len=18) "LndGetInfoResponse",
|
||||
name: (string) (len=18) "LndGetInfoResponse",
|
||||
fields: ([]*main.Field) (len=1 cap=1) {
|
||||
(*main.Field)(0xc000379350)({
|
||||
name: (string) (len=5) "alias",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
}),
|
||||
(string) (len=17) "NewAddressRequest": (*main.Message)(0xc0002151c0)({
|
||||
fullName: (string) (len=17) "NewAddressRequest",
|
||||
name: (string) (len=17) "NewAddressRequest",
|
||||
fields: ([]*main.Field) (len=1 cap=1) {
|
||||
(*main.Field)(0xc000379380)({
|
||||
name: (string) (len=12) "address_type",
|
||||
kind: (string) (len=11) "AddressType",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) true,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
}),
|
||||
(string) (len=17) "NewInvoiceRequest": (*main.Message)(0xc0002152c0)({
|
||||
fullName: (string) (len=17) "NewInvoiceRequest",
|
||||
name: (string) (len=17) "NewInvoiceRequest",
|
||||
fields: ([]*main.Field) (len=1 cap=1) {
|
||||
(*main.Field)(0xc000379470)({
|
||||
name: (string) (len=11) "amount_sats",
|
||||
kind: (string) (len=5) "int64",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
}),
|
||||
(string) (len=18) "PayInvoiceResponse": (*main.Message)(0xc000215380)({
|
||||
fullName: (string) (len=18) "PayInvoiceResponse",
|
||||
name: (string) (len=18) "PayInvoiceResponse",
|
||||
fields: ([]*main.Field) (len=1 cap=1) {
|
||||
(*main.Field)(0xc000379530)({
|
||||
name: (string) (len=8) "preimage",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
}),
|
||||
(string) (len=19) "OpenChannelResponse": (*main.Message)(0xc000215400)({
|
||||
fullName: (string) (len=19) "OpenChannelResponse",
|
||||
name: (string) (len=19) "OpenChannelResponse",
|
||||
fields: ([]*main.Field) (len=1 cap=1) {
|
||||
(*main.Field)(0xc000379620)({
|
||||
name: (string) (len=10) "channel_id",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
}),
|
||||
(string) (len=18) "PayAddressResponse": (*main.Message)(0xc000215280)({
|
||||
fullName: (string) (len=18) "PayAddressResponse",
|
||||
name: (string) (len=18) "PayAddressResponse",
|
||||
fields: ([]*main.Field) (len=1 cap=1) {
|
||||
(*main.Field)(0xc000379440)({
|
||||
name: (string) (len=5) "tx_id",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
}),
|
||||
(string) (len=17) "PayInvoiceRequest": (*main.Message)(0xc000215340)({
|
||||
fullName: (string) (len=17) "PayInvoiceRequest",
|
||||
name: (string) (len=17) "PayInvoiceRequest",
|
||||
fields: ([]*main.Field) (len=2 cap=2) {
|
||||
(*main.Field)(0xc0003794d0)({
|
||||
name: (string) (len=7) "invoice",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
}),
|
||||
(*main.Field)(0xc000379500)({
|
||||
name: (string) (len=6) "amount",
|
||||
kind: (string) (len=5) "int64",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
}),
|
||||
(string) (len=25) "EncryptionExchangeRequest": (*main.Message)(0xc000215100)({
|
||||
fullName: (string) (len=25) "EncryptionExchangeRequest",
|
||||
name: (string) (len=25) "EncryptionExchangeRequest",
|
||||
fields: ([]*main.Field) (len=2 cap=2) {
|
||||
(*main.Field)(0xc0003792c0)({
|
||||
name: (string) (len=10) "public_key",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
}),
|
||||
(*main.Field)(0xc0003792f0)({
|
||||
name: (string) (len=9) "device_id",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
}),
|
||||
(string) (len=18) "NewAddressResponse": (*main.Message)(0xc000215200)({
|
||||
fullName: (string) (len=18) "NewAddressResponse",
|
||||
name: (string) (len=18) "NewAddressResponse",
|
||||
fields: ([]*main.Field) (len=1 cap=1) {
|
||||
(*main.Field)(0xc0003793b0)({
|
||||
name: (string) (len=7) "address",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
}),
|
||||
(string) (len=27) "GetOpenChannelLNURLResponse": (*main.Message)(0xc000215440)({
|
||||
fullName: (string) (len=27) "GetOpenChannelLNURLResponse",
|
||||
name: (string) (len=27) "GetOpenChannelLNURLResponse",
|
||||
fields: ([]*main.Field) (len=1 cap=1) {
|
||||
(*main.Field)(0xc000379650)({
|
||||
name: (string) (len=5) "lnurl",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
}),
|
||||
(string) (len=14) "AddUserRequest": (*main.Message)(0xc000215480)({
|
||||
fullName: (string) (len=14) "AddUserRequest",
|
||||
name: (string) (len=14) "AddUserRequest",
|
||||
fields: ([]*main.Field) (len=3 cap=4) {
|
||||
(*main.Field)(0xc000379680)({
|
||||
name: (string) (len=12) "callback_url",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
}),
|
||||
(*main.Field)(0xc0003796b0)({
|
||||
name: (string) (len=4) "name",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
}),
|
||||
(*main.Field)(0xc0003796e0)({
|
||||
name: (string) (len=6) "secret",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
}),
|
||||
(string) (len=15) "AddUserResponse": (*main.Message)(0xc0002154c0)({
|
||||
fullName: (string) (len=15) "AddUserResponse",
|
||||
name: (string) (len=15) "AddUserResponse",
|
||||
fields: ([]*main.Field) (len=2 cap=2) {
|
||||
(*main.Field)(0xc000379710)({
|
||||
name: (string) (len=7) "user_id",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
}),
|
||||
(*main.Field)(0xc000379740)({
|
||||
name: (string) (len=10) "auth_token",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
}),
|
||||
(string) (len=15) "AuthUserRequest": (*main.Message)(0xc000215500)({
|
||||
fullName: (string) (len=15) "AuthUserRequest",
|
||||
name: (string) (len=15) "AuthUserRequest",
|
||||
fields: ([]*main.Field) (len=2 cap=2) {
|
||||
(*main.Field)(0xc000379770)({
|
||||
name: (string) (len=4) "name",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
}),
|
||||
(*main.Field)(0xc0003797a0)({
|
||||
name: (string) (len=6) "secret",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
}),
|
||||
(string) (len=16) "AuthUserResponse": (*main.Message)(0xc000215540)({
|
||||
fullName: (string) (len=16) "AuthUserResponse",
|
||||
name: (string) (len=16) "AuthUserResponse",
|
||||
fields: ([]*main.Field) (len=2 cap=2) {
|
||||
(*main.Field)(0xc0003797d0)({
|
||||
name: (string) (len=7) "user_id",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
}),
|
||||
(*main.Field)(0xc000379800)({
|
||||
name: (string) (len=10) "auth_token",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
}),
|
||||
(string) (len=5) "Empty": (*main.Message)(0xc0002150c0)({
|
||||
fullName: (string) (len=5) "Empty",
|
||||
name: (string) (len=5) "Empty",
|
||||
fields: ([]*main.Field) <nil>
|
||||
}),
|
||||
(string) (len=17) "PayAddressRequest": (*main.Message)(0xc000215240)({
|
||||
fullName: (string) (len=17) "PayAddressRequest",
|
||||
name: (string) (len=17) "PayAddressRequest",
|
||||
fields: ([]*main.Field) (len=2 cap=2) {
|
||||
(*main.Field)(0xc0003793e0)({
|
||||
name: (string) (len=7) "address",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
}),
|
||||
(*main.Field)(0xc000379410)({
|
||||
name: (string) (len=10) "amout_sats",
|
||||
kind: (string) (len=5) "int64",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
}),
|
||||
(string) (len=18) "NewInvoiceResponse": (*main.Message)(0xc000215300)({
|
||||
fullName: (string) (len=18) "NewInvoiceResponse",
|
||||
name: (string) (len=18) "NewInvoiceResponse",
|
||||
fields: ([]*main.Field) (len=1 cap=1) {
|
||||
(*main.Field)(0xc0003794a0)({
|
||||
name: (string) (len=7) "invoice",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
}),
|
||||
(string) (len=18) "OpenChannelRequest": (*main.Message)(0xc0002153c0)({
|
||||
fullName: (string) (len=18) "OpenChannelRequest",
|
||||
name: (string) (len=18) "OpenChannelRequest",
|
||||
fields: ([]*main.Field) (len=4 cap=4) {
|
||||
(*main.Field)(0xc000379560)({
|
||||
name: (string) (len=11) "destination",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
}),
|
||||
(*main.Field)(0xc000379590)({
|
||||
name: (string) (len=14) "funding_amount",
|
||||
kind: (string) (len=5) "int64",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
}),
|
||||
(*main.Field)(0xc0003795c0)({
|
||||
name: (string) (len=11) "push_amount",
|
||||
kind: (string) (len=5) "int64",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
}),
|
||||
(*main.Field)(0xc0003795f0)({
|
||||
name: (string) (len=13) "close_address",
|
||||
kind: (string) (len=6) "string",
|
||||
isMap: (bool) false,
|
||||
isArray: (bool) false,
|
||||
isEnum: (bool) false,
|
||||
isMessage: (bool) false,
|
||||
isOptional: (bool) false
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
parsing file: structs 19
|
||||
parsing file: methods 2
|
||||
-> [{guest Guest false map[]} {user User false map[user_id:string]} {admin Admin true map[admin_id:string]}]
|
||||
|
||||
186
proto/autogenerated/ts/express_server.ts
Normal file
186
proto/autogenerated/ts/express_server.ts
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
// This file was autogenerated from a .proto file, DO NOT EDIT!
|
||||
|
||||
import express, { Response, json, urlencoded } from 'express'
|
||||
import cors from 'cors'
|
||||
import * as Types from './types'
|
||||
export type Logger = { log: (v: any) => void, error: (v: any) => void }
|
||||
export type ServerOptions = {
|
||||
allowCors?: true
|
||||
staticFiles?: string
|
||||
allowNotImplementedMethods?: number
|
||||
logger?: Logger
|
||||
throwErrors?: true
|
||||
GuestAuthGuard: (authorizationHeader?: string) => Promise<Types.GuestContext>
|
||||
UserAuthGuard: (authorizationHeader?: string) => Promise<Types.UserContext>
|
||||
AdminAuthGuard: (authorizationHeader?: string) => Promise<Types.AdminContext>
|
||||
decryptCallback: (encryptionDeviceId: string, body: any) => Promise<any>
|
||||
encryptCallback: (encryptionDeviceId: string, plain: any) => Promise<any>
|
||||
}
|
||||
const logErrorAndReturnResponse = (error: Error, response: string, res: Response, logger: Logger) => { logger.error(error.message || error); res.json({ status: 'ERROR', reason: response }) }
|
||||
export default (methods: Types.ServerMethods, opts: ServerOptions) => {
|
||||
const logger = opts.logger || { log: console.log, error: console.error }
|
||||
const app = express()
|
||||
if (opts.allowCors) {
|
||||
app.use(cors())
|
||||
}
|
||||
app.use(json())
|
||||
app.use(urlencoded({ extended: true }))
|
||||
if (!opts.allowNotImplementedMethods && !methods.Health) throw new Error('method: Health is not implemented')
|
||||
app.get('/api/health', async (req, res) => {
|
||||
try {
|
||||
if (!methods.Health) throw new Error('method: Health is not implemented')
|
||||
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
|
||||
const query = req.query
|
||||
const params = req.params
|
||||
await methods.Health({ ...authContext, ...query, ...params })
|
||||
res.json({status: 'OK'})
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
|
||||
})
|
||||
if (!opts.allowNotImplementedMethods && !methods.EncryptionExchange) throw new Error('method: EncryptionExchange is not implemented')
|
||||
app.post('/api/encryption/exchange', async (req, res) => {
|
||||
try {
|
||||
if (!methods.EncryptionExchange) throw new Error('method: EncryptionExchange is not implemented')
|
||||
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
|
||||
const request = req.body
|
||||
const error = Types.EncryptionExchangeRequestValidate(request)
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
|
||||
const query = req.query
|
||||
const params = req.params
|
||||
await methods.EncryptionExchange({ ...authContext, ...query, ...params }, request)
|
||||
res.json({status: 'OK'})
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
|
||||
})
|
||||
if (!opts.allowNotImplementedMethods && !methods.LndGetInfo) throw new Error('method: LndGetInfo is not implemented')
|
||||
app.post('/api/lnd/getinfo', async (req, res) => {
|
||||
try {
|
||||
if (!methods.LndGetInfo) throw new Error('method: LndGetInfo is not implemented')
|
||||
const authContext = await opts.AdminAuthGuard(req.headers['authorization'])
|
||||
const encryptionDeviceId = req.headers['x-e2ee-device-id-x']
|
||||
if (typeof encryptionDeviceId !== 'string' || encryptionDeviceId === '') throw new Error('invalid encryption header provided')
|
||||
const request = await opts.decryptCallback(encryptionDeviceId, req.body)
|
||||
const error = Types.LndGetInfoRequestValidate(request)
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
|
||||
const query = req.query
|
||||
const params = req.params
|
||||
const response = await methods.LndGetInfo({ ...authContext, ...query, ...params }, request)
|
||||
res.json({status: 'OK', result: await opts.encryptCallback(encryptionDeviceId, response)})
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
|
||||
})
|
||||
if (!opts.allowNotImplementedMethods && !methods.AddUser) throw new Error('method: AddUser is not implemented')
|
||||
app.post('/api/user/add', async (req, res) => {
|
||||
try {
|
||||
if (!methods.AddUser) throw new Error('method: AddUser is not implemented')
|
||||
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
|
||||
const request = req.body
|
||||
const error = Types.AddUserRequestValidate(request)
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
|
||||
const query = req.query
|
||||
const params = req.params
|
||||
const response = await methods.AddUser({ ...authContext, ...query, ...params }, request)
|
||||
res.json({status: 'OK', result: response})
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
|
||||
})
|
||||
if (!opts.allowNotImplementedMethods && !methods.AuthUser) throw new Error('method: AuthUser is not implemented')
|
||||
app.post('/api/user/auth', async (req, res) => {
|
||||
try {
|
||||
if (!methods.AuthUser) throw new Error('method: AuthUser is not implemented')
|
||||
const authContext = await opts.GuestAuthGuard(req.headers['authorization'])
|
||||
const request = req.body
|
||||
const error = Types.AuthUserRequestValidate(request)
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
|
||||
const query = req.query
|
||||
const params = req.params
|
||||
const response = await methods.AuthUser({ ...authContext, ...query, ...params }, request)
|
||||
res.json({status: 'OK', result: response})
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
|
||||
})
|
||||
if (!opts.allowNotImplementedMethods && !methods.NewAddress) throw new Error('method: NewAddress is not implemented')
|
||||
app.post('/api/user/chain/new', async (req, res) => {
|
||||
try {
|
||||
if (!methods.NewAddress) throw new Error('method: NewAddress is not implemented')
|
||||
const authContext = await opts.UserAuthGuard(req.headers['authorization'])
|
||||
const request = req.body
|
||||
const error = Types.NewAddressRequestValidate(request)
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
|
||||
const query = req.query
|
||||
const params = req.params
|
||||
const response = await methods.NewAddress({ ...authContext, ...query, ...params }, request)
|
||||
res.json({status: 'OK', result: response})
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
|
||||
})
|
||||
if (!opts.allowNotImplementedMethods && !methods.PayAddress) throw new Error('method: PayAddress is not implemented')
|
||||
app.post('/api/user/chain/pay', async (req, res) => {
|
||||
try {
|
||||
if (!methods.PayAddress) throw new Error('method: PayAddress is not implemented')
|
||||
const authContext = await opts.UserAuthGuard(req.headers['authorization'])
|
||||
const request = req.body
|
||||
const error = Types.PayAddressRequestValidate(request)
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
|
||||
const query = req.query
|
||||
const params = req.params
|
||||
const response = await methods.PayAddress({ ...authContext, ...query, ...params }, request)
|
||||
res.json({status: 'OK', result: response})
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
|
||||
})
|
||||
if (!opts.allowNotImplementedMethods && !methods.NewInvoice) throw new Error('method: NewInvoice is not implemented')
|
||||
app.post('/api/user/invoice/new', async (req, res) => {
|
||||
try {
|
||||
if (!methods.NewInvoice) throw new Error('method: NewInvoice is not implemented')
|
||||
const authContext = await opts.UserAuthGuard(req.headers['authorization'])
|
||||
const request = req.body
|
||||
const error = Types.NewInvoiceRequestValidate(request)
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
|
||||
const query = req.query
|
||||
const params = req.params
|
||||
const response = await methods.NewInvoice({ ...authContext, ...query, ...params }, request)
|
||||
res.json({status: 'OK', result: response})
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
|
||||
})
|
||||
if (!opts.allowNotImplementedMethods && !methods.PayInvoice) throw new Error('method: PayInvoice is not implemented')
|
||||
app.post('/api/user/invoice/pay', async (req, res) => {
|
||||
try {
|
||||
if (!methods.PayInvoice) throw new Error('method: PayInvoice is not implemented')
|
||||
const authContext = await opts.UserAuthGuard(req.headers['authorization'])
|
||||
const request = req.body
|
||||
const error = Types.PayInvoiceRequestValidate(request)
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
|
||||
const query = req.query
|
||||
const params = req.params
|
||||
const response = await methods.PayInvoice({ ...authContext, ...query, ...params }, request)
|
||||
res.json({status: 'OK', result: response})
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
|
||||
})
|
||||
if (!opts.allowNotImplementedMethods && !methods.OpenChannel) throw new Error('method: OpenChannel is not implemented')
|
||||
app.post('/api/user/open/channel', async (req, res) => {
|
||||
try {
|
||||
if (!methods.OpenChannel) throw new Error('method: OpenChannel is not implemented')
|
||||
const authContext = await opts.UserAuthGuard(req.headers['authorization'])
|
||||
const request = req.body
|
||||
const error = Types.OpenChannelRequestValidate(request)
|
||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger)
|
||||
const query = req.query
|
||||
const params = req.params
|
||||
const response = await methods.OpenChannel({ ...authContext, ...query, ...params }, request)
|
||||
res.json({status: 'OK', result: response})
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
|
||||
})
|
||||
if (!opts.allowNotImplementedMethods && !methods.GetOpenChannelLNURL) throw new Error('method: GetOpenChannelLNURL is not implemented')
|
||||
app.post('/api/user/lnurl_channel', async (req, res) => {
|
||||
try {
|
||||
if (!methods.GetOpenChannelLNURL) throw new Error('method: GetOpenChannelLNURL is not implemented')
|
||||
const authContext = await opts.UserAuthGuard(req.headers['authorization'])
|
||||
const query = req.query
|
||||
const params = req.params
|
||||
const response = await methods.GetOpenChannelLNURL({ ...authContext, ...query, ...params })
|
||||
res.json({status: 'OK', result: response})
|
||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger); if (opts.throwErrors) throw e }
|
||||
})
|
||||
if (opts.staticFiles) {
|
||||
app.use(express.static(opts.staticFiles))
|
||||
}
|
||||
var server: { close: () => void } | undefined
|
||||
return {
|
||||
Close: () => { if (!server) { throw new Error('tried closing server before starting') } else server.close() },
|
||||
Listen: (port: number) => { server = app.listen(port, () => logger.log('Example app listening on port ' + port)) }
|
||||
}
|
||||
}
|
||||
155
proto/autogenerated/ts/http_client.ts
Normal file
155
proto/autogenerated/ts/http_client.ts
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
// This file was autogenerated from a .proto file, DO NOT EDIT!
|
||||
import axios from 'axios'
|
||||
import * as Types from './types'
|
||||
export type ResultError = { status: 'ERROR', reason: string }
|
||||
|
||||
export type ClientParams = {
|
||||
baseUrl: string
|
||||
retrieveGuestAuth: () => Promise<string | null>
|
||||
retrieveUserAuth: () => Promise<string | null>
|
||||
retrieveAdminAuth: () => Promise<string | null>
|
||||
encryptCallback: (plain: any) => Promise<any>
|
||||
decryptCallback: (encrypted: any) => Promise<any>
|
||||
deviceId: string
|
||||
}
|
||||
export default (params: ClientParams) => ({
|
||||
Health: async (): Promise<ResultError | { status: 'OK' }> => {
|
||||
const auth = await params.retrieveGuestAuth()
|
||||
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
|
||||
let finalRoute = '/api/health'
|
||||
const { data } = await axios.get(params.baseUrl + finalRoute, { headers: { 'authorization': auth } })
|
||||
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
|
||||
if (data.status === 'OK') {
|
||||
return data
|
||||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
EncryptionExchange: async (request: Types.EncryptionExchangeRequest): Promise<ResultError | { status: 'OK' }> => {
|
||||
const auth = await params.retrieveGuestAuth()
|
||||
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
|
||||
let finalRoute = '/api/encryption/exchange'
|
||||
const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } })
|
||||
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
|
||||
if (data.status === 'OK') {
|
||||
return data
|
||||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
LndGetInfo: async (request: Types.LndGetInfoRequest): Promise<ResultError | { status: 'OK', result: Types.LndGetInfoResponse }> => {
|
||||
const auth = await params.retrieveAdminAuth()
|
||||
if (auth === null) throw new Error('retrieveAdminAuth() returned null')
|
||||
let finalRoute = '/api/lnd/getinfo'
|
||||
const { data } = await axios.post(params.baseUrl + finalRoute, await params.encryptCallback(request), { headers: { 'authorization': auth, 'x-e2ee-device-id-x': params.deviceId } })
|
||||
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
|
||||
if (data.status === 'OK') {
|
||||
const result = await params.decryptCallback(data.result)
|
||||
const error = Types.LndGetInfoResponseValidate(result)
|
||||
if (error === null) { return { status: 'OK', result: result } } else return { status: 'ERROR', reason: error.message }
|
||||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
AddUser: async (request: Types.AddUserRequest): Promise<ResultError | { status: 'OK', result: Types.AddUserResponse }> => {
|
||||
const auth = await params.retrieveGuestAuth()
|
||||
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
|
||||
let finalRoute = '/api/user/add'
|
||||
const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } })
|
||||
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
|
||||
if (data.status === 'OK') {
|
||||
const result = data.result
|
||||
const error = Types.AddUserResponseValidate(result)
|
||||
if (error === null) { return { status: 'OK', result: result } } else return { status: 'ERROR', reason: error.message }
|
||||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
AuthUser: async (request: Types.AuthUserRequest): Promise<ResultError | { status: 'OK', result: Types.AuthUserResponse }> => {
|
||||
const auth = await params.retrieveGuestAuth()
|
||||
if (auth === null) throw new Error('retrieveGuestAuth() returned null')
|
||||
let finalRoute = '/api/user/auth'
|
||||
const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } })
|
||||
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
|
||||
if (data.status === 'OK') {
|
||||
const result = data.result
|
||||
const error = Types.AuthUserResponseValidate(result)
|
||||
if (error === null) { return { status: 'OK', result: result } } else return { status: 'ERROR', reason: error.message }
|
||||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
NewAddress: async (request: Types.NewAddressRequest): Promise<ResultError | { status: 'OK', result: Types.NewAddressResponse }> => {
|
||||
const auth = await params.retrieveUserAuth()
|
||||
if (auth === null) throw new Error('retrieveUserAuth() returned null')
|
||||
let finalRoute = '/api/user/chain/new'
|
||||
const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } })
|
||||
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
|
||||
if (data.status === 'OK') {
|
||||
const result = data.result
|
||||
const error = Types.NewAddressResponseValidate(result)
|
||||
if (error === null) { return { status: 'OK', result: result } } else return { status: 'ERROR', reason: error.message }
|
||||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
PayAddress: async (request: Types.PayAddressRequest): Promise<ResultError | { status: 'OK', result: Types.PayAddressResponse }> => {
|
||||
const auth = await params.retrieveUserAuth()
|
||||
if (auth === null) throw new Error('retrieveUserAuth() returned null')
|
||||
let finalRoute = '/api/user/chain/pay'
|
||||
const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } })
|
||||
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
|
||||
if (data.status === 'OK') {
|
||||
const result = data.result
|
||||
const error = Types.PayAddressResponseValidate(result)
|
||||
if (error === null) { return { status: 'OK', result: result } } else return { status: 'ERROR', reason: error.message }
|
||||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
NewInvoice: async (request: Types.NewInvoiceRequest): Promise<ResultError | { status: 'OK', result: Types.NewInvoiceResponse }> => {
|
||||
const auth = await params.retrieveUserAuth()
|
||||
if (auth === null) throw new Error('retrieveUserAuth() returned null')
|
||||
let finalRoute = '/api/user/invoice/new'
|
||||
const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } })
|
||||
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
|
||||
if (data.status === 'OK') {
|
||||
const result = data.result
|
||||
const error = Types.NewInvoiceResponseValidate(result)
|
||||
if (error === null) { return { status: 'OK', result: result } } else return { status: 'ERROR', reason: error.message }
|
||||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
PayInvoice: async (request: Types.PayInvoiceRequest): Promise<ResultError | { status: 'OK', result: Types.PayInvoiceResponse }> => {
|
||||
const auth = await params.retrieveUserAuth()
|
||||
if (auth === null) throw new Error('retrieveUserAuth() returned null')
|
||||
let finalRoute = '/api/user/invoice/pay'
|
||||
const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } })
|
||||
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
|
||||
if (data.status === 'OK') {
|
||||
const result = data.result
|
||||
const error = Types.PayInvoiceResponseValidate(result)
|
||||
if (error === null) { return { status: 'OK', result: result } } else return { status: 'ERROR', reason: error.message }
|
||||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
OpenChannel: async (request: Types.OpenChannelRequest): Promise<ResultError | { status: 'OK', result: Types.OpenChannelResponse }> => {
|
||||
const auth = await params.retrieveUserAuth()
|
||||
if (auth === null) throw new Error('retrieveUserAuth() returned null')
|
||||
let finalRoute = '/api/user/open/channel'
|
||||
const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } })
|
||||
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
|
||||
if (data.status === 'OK') {
|
||||
const result = data.result
|
||||
const error = Types.OpenChannelResponseValidate(result)
|
||||
if (error === null) { return { status: 'OK', result: result } } else return { status: 'ERROR', reason: error.message }
|
||||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
GetOpenChannelLNURL: async (): Promise<ResultError | { status: 'OK', result: Types.GetOpenChannelLNURLResponse }> => {
|
||||
const auth = await params.retrieveUserAuth()
|
||||
if (auth === null) throw new Error('retrieveUserAuth() returned null')
|
||||
let finalRoute = '/api/user/lnurl_channel'
|
||||
const { data } = await axios.post(params.baseUrl + finalRoute, {}, { headers: { 'authorization': auth } })
|
||||
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
|
||||
if (data.status === 'OK') {
|
||||
const result = data.result
|
||||
const error = Types.GetOpenChannelLNURLResponseValidate(result)
|
||||
if (error === null) { return { status: 'OK', result: result } } else return { status: 'ERROR', reason: error.message }
|
||||
}
|
||||
return { status: 'ERROR', reason: 'invalid response' }
|
||||
},
|
||||
})
|
||||
487
proto/autogenerated/ts/types.ts
Normal file
487
proto/autogenerated/ts/types.ts
Normal file
|
|
@ -0,0 +1,487 @@
|
|||
// This file was autogenerated from a .proto file, DO NOT EDIT!
|
||||
|
||||
export type GuestContext = {
|
||||
}
|
||||
export type UserContext = {
|
||||
user_id: string
|
||||
}
|
||||
export type AdminContext = {
|
||||
admin_id: string
|
||||
}
|
||||
export type AuthContext = GuestContext | UserContext | AdminContext
|
||||
|
||||
export type Health_Query = {
|
||||
}
|
||||
export type Health_RouteParams = {
|
||||
}
|
||||
export type Health_Context = Health_Query & Health_RouteParams & GuestContext
|
||||
export type EncryptionExchange_Query = {
|
||||
}
|
||||
export type EncryptionExchange_RouteParams = {
|
||||
}
|
||||
export type EncryptionExchange_Context = EncryptionExchange_Query & EncryptionExchange_RouteParams & GuestContext
|
||||
export type LndGetInfo_Query = {
|
||||
}
|
||||
export type LndGetInfo_RouteParams = {
|
||||
}
|
||||
export type LndGetInfo_Context = LndGetInfo_Query & LndGetInfo_RouteParams & AdminContext
|
||||
export type AddUser_Query = {
|
||||
}
|
||||
export type AddUser_RouteParams = {
|
||||
}
|
||||
export type AddUser_Context = AddUser_Query & AddUser_RouteParams & GuestContext
|
||||
export type AuthUser_Query = {
|
||||
}
|
||||
export type AuthUser_RouteParams = {
|
||||
}
|
||||
export type AuthUser_Context = AuthUser_Query & AuthUser_RouteParams & GuestContext
|
||||
export type NewAddress_Query = {
|
||||
}
|
||||
export type NewAddress_RouteParams = {
|
||||
}
|
||||
export type NewAddress_Context = NewAddress_Query & NewAddress_RouteParams & UserContext
|
||||
export type PayAddress_Query = {
|
||||
}
|
||||
export type PayAddress_RouteParams = {
|
||||
}
|
||||
export type PayAddress_Context = PayAddress_Query & PayAddress_RouteParams & UserContext
|
||||
export type NewInvoice_Query = {
|
||||
}
|
||||
export type NewInvoice_RouteParams = {
|
||||
}
|
||||
export type NewInvoice_Context = NewInvoice_Query & NewInvoice_RouteParams & UserContext
|
||||
export type PayInvoice_Query = {
|
||||
}
|
||||
export type PayInvoice_RouteParams = {
|
||||
}
|
||||
export type PayInvoice_Context = PayInvoice_Query & PayInvoice_RouteParams & UserContext
|
||||
export type OpenChannel_Query = {
|
||||
}
|
||||
export type OpenChannel_RouteParams = {
|
||||
}
|
||||
export type OpenChannel_Context = OpenChannel_Query & OpenChannel_RouteParams & UserContext
|
||||
export type GetOpenChannelLNURL_Query = {
|
||||
}
|
||||
export type GetOpenChannelLNURL_RouteParams = {
|
||||
}
|
||||
export type GetOpenChannelLNURL_Context = GetOpenChannelLNURL_Query & GetOpenChannelLNURL_RouteParams & UserContext
|
||||
export type ServerMethods = {
|
||||
Health?: (ctx: Health_Context) => Promise<void>
|
||||
EncryptionExchange?: (ctx: EncryptionExchange_Context, req: EncryptionExchangeRequest) => Promise<void>
|
||||
LndGetInfo?: (ctx: LndGetInfo_Context, req: LndGetInfoRequest) => Promise<LndGetInfoResponse>
|
||||
AddUser?: (ctx: AddUser_Context, req: AddUserRequest) => Promise<AddUserResponse>
|
||||
AuthUser?: (ctx: AuthUser_Context, req: AuthUserRequest) => Promise<AuthUserResponse>
|
||||
NewAddress?: (ctx: NewAddress_Context, req: NewAddressRequest) => Promise<NewAddressResponse>
|
||||
PayAddress?: (ctx: PayAddress_Context, req: PayAddressRequest) => Promise<PayAddressResponse>
|
||||
NewInvoice?: (ctx: NewInvoice_Context, req: NewInvoiceRequest) => Promise<NewInvoiceResponse>
|
||||
PayInvoice?: (ctx: PayInvoice_Context, req: PayInvoiceRequest) => Promise<PayInvoiceResponse>
|
||||
OpenChannel?: (ctx: OpenChannel_Context, req: OpenChannelRequest) => Promise<OpenChannelResponse>
|
||||
GetOpenChannelLNURL?: (ctx: GetOpenChannelLNURL_Context) => Promise<GetOpenChannelLNURLResponse>
|
||||
}
|
||||
|
||||
export enum AddressType {
|
||||
WITNESS_PUBKEY_HASH = 'WITNESS_PUBKEY_HASH',
|
||||
NESTED_PUBKEY_HASH = 'NESTED_PUBKEY_HASH',
|
||||
TAPROOT_PUBKEY = 'TAPROOT_PUBKEY',
|
||||
}
|
||||
const enumCheckAddressType = (e?: AddressType): boolean => {
|
||||
for (const v in AddressType) if (e === v) return true
|
||||
return false
|
||||
}
|
||||
|
||||
export type OptionsBaseMessage = {
|
||||
allOptionalsAreSet?: true
|
||||
}
|
||||
|
||||
export type Empty = {
|
||||
}
|
||||
export const EmptyOptionalFields: [] = []
|
||||
export type EmptyOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
}
|
||||
export const EmptyValidate = (o?: Empty, opts: EmptyOptions = {}, path: string = 'Empty::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type PayAddressRequest = {
|
||||
address: string
|
||||
amout_sats: number
|
||||
}
|
||||
export const PayAddressRequestOptionalFields: [] = []
|
||||
export type PayAddressRequestOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
address_CustomCheck?: (v: string) => boolean
|
||||
amout_sats_CustomCheck?: (v: number) => boolean
|
||||
}
|
||||
export const PayAddressRequestValidate = (o?: PayAddressRequest, opts: PayAddressRequestOptions = {}, path: string = 'PayAddressRequest::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (typeof o.address !== 'string') return new Error(`${path}.address: is not a string`)
|
||||
if (opts.address_CustomCheck && !opts.address_CustomCheck(o.address)) return new Error(`${path}.address: custom check failed`)
|
||||
|
||||
if (typeof o.amout_sats !== 'number') return new Error(`${path}.amout_sats: is not a number`)
|
||||
if (opts.amout_sats_CustomCheck && !opts.amout_sats_CustomCheck(o.amout_sats)) return new Error(`${path}.amout_sats: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type NewInvoiceResponse = {
|
||||
invoice: string
|
||||
}
|
||||
export const NewInvoiceResponseOptionalFields: [] = []
|
||||
export type NewInvoiceResponseOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
invoice_CustomCheck?: (v: string) => boolean
|
||||
}
|
||||
export const NewInvoiceResponseValidate = (o?: NewInvoiceResponse, opts: NewInvoiceResponseOptions = {}, path: string = 'NewInvoiceResponse::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (typeof o.invoice !== 'string') return new Error(`${path}.invoice: is not a string`)
|
||||
if (opts.invoice_CustomCheck && !opts.invoice_CustomCheck(o.invoice)) return new Error(`${path}.invoice: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type OpenChannelRequest = {
|
||||
destination: string
|
||||
funding_amount: number
|
||||
push_amount: number
|
||||
close_address: string
|
||||
}
|
||||
export const OpenChannelRequestOptionalFields: [] = []
|
||||
export type OpenChannelRequestOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
destination_CustomCheck?: (v: string) => boolean
|
||||
funding_amount_CustomCheck?: (v: number) => boolean
|
||||
push_amount_CustomCheck?: (v: number) => boolean
|
||||
close_address_CustomCheck?: (v: string) => boolean
|
||||
}
|
||||
export const OpenChannelRequestValidate = (o?: OpenChannelRequest, opts: OpenChannelRequestOptions = {}, path: string = 'OpenChannelRequest::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (typeof o.destination !== 'string') return new Error(`${path}.destination: is not a string`)
|
||||
if (opts.destination_CustomCheck && !opts.destination_CustomCheck(o.destination)) return new Error(`${path}.destination: custom check failed`)
|
||||
|
||||
if (typeof o.funding_amount !== 'number') return new Error(`${path}.funding_amount: is not a number`)
|
||||
if (opts.funding_amount_CustomCheck && !opts.funding_amount_CustomCheck(o.funding_amount)) return new Error(`${path}.funding_amount: custom check failed`)
|
||||
|
||||
if (typeof o.push_amount !== 'number') return new Error(`${path}.push_amount: is not a number`)
|
||||
if (opts.push_amount_CustomCheck && !opts.push_amount_CustomCheck(o.push_amount)) return new Error(`${path}.push_amount: custom check failed`)
|
||||
|
||||
if (typeof o.close_address !== 'string') return new Error(`${path}.close_address: is not a string`)
|
||||
if (opts.close_address_CustomCheck && !opts.close_address_CustomCheck(o.close_address)) return new Error(`${path}.close_address: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type OpenChannelResponse = {
|
||||
channel_id: string
|
||||
}
|
||||
export const OpenChannelResponseOptionalFields: [] = []
|
||||
export type OpenChannelResponseOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
channel_id_CustomCheck?: (v: string) => boolean
|
||||
}
|
||||
export const OpenChannelResponseValidate = (o?: OpenChannelResponse, opts: OpenChannelResponseOptions = {}, path: string = 'OpenChannelResponse::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (typeof o.channel_id !== 'string') return new Error(`${path}.channel_id: is not a string`)
|
||||
if (opts.channel_id_CustomCheck && !opts.channel_id_CustomCheck(o.channel_id)) return new Error(`${path}.channel_id: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type LndGetInfoRequest = {
|
||||
node_id: number
|
||||
}
|
||||
export const LndGetInfoRequestOptionalFields: [] = []
|
||||
export type LndGetInfoRequestOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
node_id_CustomCheck?: (v: number) => boolean
|
||||
}
|
||||
export const LndGetInfoRequestValidate = (o?: LndGetInfoRequest, opts: LndGetInfoRequestOptions = {}, path: string = 'LndGetInfoRequest::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (typeof o.node_id !== 'number') return new Error(`${path}.node_id: is not a number`)
|
||||
if (opts.node_id_CustomCheck && !opts.node_id_CustomCheck(o.node_id)) return new Error(`${path}.node_id: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type LndGetInfoResponse = {
|
||||
alias: string
|
||||
}
|
||||
export const LndGetInfoResponseOptionalFields: [] = []
|
||||
export type LndGetInfoResponseOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
alias_CustomCheck?: (v: string) => boolean
|
||||
}
|
||||
export const LndGetInfoResponseValidate = (o?: LndGetInfoResponse, opts: LndGetInfoResponseOptions = {}, path: string = 'LndGetInfoResponse::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (typeof o.alias !== 'string') return new Error(`${path}.alias: is not a string`)
|
||||
if (opts.alias_CustomCheck && !opts.alias_CustomCheck(o.alias)) return new Error(`${path}.alias: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type NewAddressRequest = {
|
||||
address_type: AddressType
|
||||
}
|
||||
export const NewAddressRequestOptionalFields: [] = []
|
||||
export type NewAddressRequestOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
address_type_CustomCheck?: (v: AddressType) => boolean
|
||||
}
|
||||
export const NewAddressRequestValidate = (o?: NewAddressRequest, opts: NewAddressRequestOptions = {}, path: string = 'NewAddressRequest::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (!enumCheckAddressType(o.address_type)) return new Error(`${path}.address_type: is not a valid AddressType`)
|
||||
if (opts.address_type_CustomCheck && !opts.address_type_CustomCheck(o.address_type)) return new Error(`${path}.address_type: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type NewInvoiceRequest = {
|
||||
amount_sats: number
|
||||
}
|
||||
export const NewInvoiceRequestOptionalFields: [] = []
|
||||
export type NewInvoiceRequestOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
amount_sats_CustomCheck?: (v: number) => boolean
|
||||
}
|
||||
export const NewInvoiceRequestValidate = (o?: NewInvoiceRequest, opts: NewInvoiceRequestOptions = {}, path: string = 'NewInvoiceRequest::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (typeof o.amount_sats !== 'number') return new Error(`${path}.amount_sats: is not a number`)
|
||||
if (opts.amount_sats_CustomCheck && !opts.amount_sats_CustomCheck(o.amount_sats)) return new Error(`${path}.amount_sats: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type PayInvoiceResponse = {
|
||||
preimage: string
|
||||
}
|
||||
export const PayInvoiceResponseOptionalFields: [] = []
|
||||
export type PayInvoiceResponseOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
preimage_CustomCheck?: (v: string) => boolean
|
||||
}
|
||||
export const PayInvoiceResponseValidate = (o?: PayInvoiceResponse, opts: PayInvoiceResponseOptions = {}, path: string = 'PayInvoiceResponse::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (typeof o.preimage !== 'string') return new Error(`${path}.preimage: is not a string`)
|
||||
if (opts.preimage_CustomCheck && !opts.preimage_CustomCheck(o.preimage)) return new Error(`${path}.preimage: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type PayAddressResponse = {
|
||||
tx_id: string
|
||||
}
|
||||
export const PayAddressResponseOptionalFields: [] = []
|
||||
export type PayAddressResponseOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
tx_id_CustomCheck?: (v: string) => boolean
|
||||
}
|
||||
export const PayAddressResponseValidate = (o?: PayAddressResponse, opts: PayAddressResponseOptions = {}, path: string = 'PayAddressResponse::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (typeof o.tx_id !== 'string') return new Error(`${path}.tx_id: is not a string`)
|
||||
if (opts.tx_id_CustomCheck && !opts.tx_id_CustomCheck(o.tx_id)) return new Error(`${path}.tx_id: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type PayInvoiceRequest = {
|
||||
invoice: string
|
||||
amount: number
|
||||
}
|
||||
export const PayInvoiceRequestOptionalFields: [] = []
|
||||
export type PayInvoiceRequestOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
invoice_CustomCheck?: (v: string) => boolean
|
||||
amount_CustomCheck?: (v: number) => boolean
|
||||
}
|
||||
export const PayInvoiceRequestValidate = (o?: PayInvoiceRequest, opts: PayInvoiceRequestOptions = {}, path: string = 'PayInvoiceRequest::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (typeof o.invoice !== 'string') return new Error(`${path}.invoice: is not a string`)
|
||||
if (opts.invoice_CustomCheck && !opts.invoice_CustomCheck(o.invoice)) return new Error(`${path}.invoice: custom check failed`)
|
||||
|
||||
if (typeof o.amount !== 'number') return new Error(`${path}.amount: is not a number`)
|
||||
if (opts.amount_CustomCheck && !opts.amount_CustomCheck(o.amount)) return new Error(`${path}.amount: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type AuthUserRequest = {
|
||||
name: string
|
||||
secret: string
|
||||
}
|
||||
export const AuthUserRequestOptionalFields: [] = []
|
||||
export type AuthUserRequestOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
name_CustomCheck?: (v: string) => boolean
|
||||
secret_CustomCheck?: (v: string) => boolean
|
||||
}
|
||||
export const AuthUserRequestValidate = (o?: AuthUserRequest, opts: AuthUserRequestOptions = {}, path: string = 'AuthUserRequest::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (typeof o.name !== 'string') return new Error(`${path}.name: is not a string`)
|
||||
if (opts.name_CustomCheck && !opts.name_CustomCheck(o.name)) return new Error(`${path}.name: custom check failed`)
|
||||
|
||||
if (typeof o.secret !== 'string') return new Error(`${path}.secret: is not a string`)
|
||||
if (opts.secret_CustomCheck && !opts.secret_CustomCheck(o.secret)) return new Error(`${path}.secret: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type AuthUserResponse = {
|
||||
user_id: string
|
||||
auth_token: string
|
||||
}
|
||||
export const AuthUserResponseOptionalFields: [] = []
|
||||
export type AuthUserResponseOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
user_id_CustomCheck?: (v: string) => boolean
|
||||
auth_token_CustomCheck?: (v: string) => boolean
|
||||
}
|
||||
export const AuthUserResponseValidate = (o?: AuthUserResponse, opts: AuthUserResponseOptions = {}, path: string = 'AuthUserResponse::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (typeof o.user_id !== 'string') return new Error(`${path}.user_id: is not a string`)
|
||||
if (opts.user_id_CustomCheck && !opts.user_id_CustomCheck(o.user_id)) return new Error(`${path}.user_id: custom check failed`)
|
||||
|
||||
if (typeof o.auth_token !== 'string') return new Error(`${path}.auth_token: is not a string`)
|
||||
if (opts.auth_token_CustomCheck && !opts.auth_token_CustomCheck(o.auth_token)) return new Error(`${path}.auth_token: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type EncryptionExchangeRequest = {
|
||||
public_key: string
|
||||
device_id: string
|
||||
}
|
||||
export const EncryptionExchangeRequestOptionalFields: [] = []
|
||||
export type EncryptionExchangeRequestOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
public_key_CustomCheck?: (v: string) => boolean
|
||||
device_id_CustomCheck?: (v: string) => boolean
|
||||
}
|
||||
export const EncryptionExchangeRequestValidate = (o?: EncryptionExchangeRequest, opts: EncryptionExchangeRequestOptions = {}, path: string = 'EncryptionExchangeRequest::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (typeof o.public_key !== 'string') return new Error(`${path}.public_key: is not a string`)
|
||||
if (opts.public_key_CustomCheck && !opts.public_key_CustomCheck(o.public_key)) return new Error(`${path}.public_key: custom check failed`)
|
||||
|
||||
if (typeof o.device_id !== 'string') return new Error(`${path}.device_id: is not a string`)
|
||||
if (opts.device_id_CustomCheck && !opts.device_id_CustomCheck(o.device_id)) return new Error(`${path}.device_id: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type NewAddressResponse = {
|
||||
address: string
|
||||
}
|
||||
export const NewAddressResponseOptionalFields: [] = []
|
||||
export type NewAddressResponseOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
address_CustomCheck?: (v: string) => boolean
|
||||
}
|
||||
export const NewAddressResponseValidate = (o?: NewAddressResponse, opts: NewAddressResponseOptions = {}, path: string = 'NewAddressResponse::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (typeof o.address !== 'string') return new Error(`${path}.address: is not a string`)
|
||||
if (opts.address_CustomCheck && !opts.address_CustomCheck(o.address)) return new Error(`${path}.address: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type GetOpenChannelLNURLResponse = {
|
||||
lnurl: string
|
||||
}
|
||||
export const GetOpenChannelLNURLResponseOptionalFields: [] = []
|
||||
export type GetOpenChannelLNURLResponseOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
lnurl_CustomCheck?: (v: string) => boolean
|
||||
}
|
||||
export const GetOpenChannelLNURLResponseValidate = (o?: GetOpenChannelLNURLResponse, opts: GetOpenChannelLNURLResponseOptions = {}, path: string = 'GetOpenChannelLNURLResponse::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (typeof o.lnurl !== 'string') return new Error(`${path}.lnurl: is not a string`)
|
||||
if (opts.lnurl_CustomCheck && !opts.lnurl_CustomCheck(o.lnurl)) return new Error(`${path}.lnurl: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type AddUserRequest = {
|
||||
callback_url: string
|
||||
name: string
|
||||
secret: string
|
||||
}
|
||||
export const AddUserRequestOptionalFields: [] = []
|
||||
export type AddUserRequestOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
callback_url_CustomCheck?: (v: string) => boolean
|
||||
name_CustomCheck?: (v: string) => boolean
|
||||
secret_CustomCheck?: (v: string) => boolean
|
||||
}
|
||||
export const AddUserRequestValidate = (o?: AddUserRequest, opts: AddUserRequestOptions = {}, path: string = 'AddUserRequest::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (typeof o.callback_url !== 'string') return new Error(`${path}.callback_url: is not a string`)
|
||||
if (opts.callback_url_CustomCheck && !opts.callback_url_CustomCheck(o.callback_url)) return new Error(`${path}.callback_url: custom check failed`)
|
||||
|
||||
if (typeof o.name !== 'string') return new Error(`${path}.name: is not a string`)
|
||||
if (opts.name_CustomCheck && !opts.name_CustomCheck(o.name)) return new Error(`${path}.name: custom check failed`)
|
||||
|
||||
if (typeof o.secret !== 'string') return new Error(`${path}.secret: is not a string`)
|
||||
if (opts.secret_CustomCheck && !opts.secret_CustomCheck(o.secret)) return new Error(`${path}.secret: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export type AddUserResponse = {
|
||||
user_id: string
|
||||
auth_token: string
|
||||
}
|
||||
export const AddUserResponseOptionalFields: [] = []
|
||||
export type AddUserResponseOptions = OptionsBaseMessage & {
|
||||
checkOptionalsAreSet?: []
|
||||
user_id_CustomCheck?: (v: string) => boolean
|
||||
auth_token_CustomCheck?: (v: string) => boolean
|
||||
}
|
||||
export const AddUserResponseValidate = (o?: AddUserResponse, opts: AddUserResponseOptions = {}, path: string = 'AddUserResponse::root.'): Error | null => {
|
||||
if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message')
|
||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null')
|
||||
|
||||
if (typeof o.user_id !== 'string') return new Error(`${path}.user_id: is not a string`)
|
||||
if (opts.user_id_CustomCheck && !opts.user_id_CustomCheck(o.user_id)) return new Error(`${path}.user_id: custom check failed`)
|
||||
|
||||
if (typeof o.auth_token !== 'string') return new Error(`${path}.auth_token: is not a string`)
|
||||
if (opts.auth_token_CustomCheck && !opts.auth_token_CustomCheck(o.auth_token)) return new Error(`${path}.auth_token: custom check failed`)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
139
proto/lnd/invoices.client.ts
Normal file
139
proto/lnd/invoices.client.ts
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
// @generated by protobuf-ts 2.5.0
|
||||
// @generated from protobuf file "invoices.proto" (package "invoicesrpc", syntax proto3)
|
||||
// tslint:disable
|
||||
import type { RpcTransport } from "@protobuf-ts/runtime-rpc";
|
||||
import type { ServiceInfo } from "@protobuf-ts/runtime-rpc";
|
||||
import { Invoices } from "./invoices";
|
||||
import type { LookupInvoiceMsg } from "./invoices";
|
||||
import type { SettleInvoiceResp } from "./invoices";
|
||||
import type { SettleInvoiceMsg } from "./invoices";
|
||||
import type { AddHoldInvoiceResp } from "./invoices";
|
||||
import type { AddHoldInvoiceRequest } from "./invoices";
|
||||
import type { CancelInvoiceResp } from "./invoices";
|
||||
import type { CancelInvoiceMsg } from "./invoices";
|
||||
import type { UnaryCall } from "@protobuf-ts/runtime-rpc";
|
||||
import { stackIntercept } from "@protobuf-ts/runtime-rpc";
|
||||
import type { Invoice } from "./lightning";
|
||||
import type { SubscribeSingleInvoiceRequest } from "./invoices";
|
||||
import type { ServerStreamingCall } from "@protobuf-ts/runtime-rpc";
|
||||
import type { RpcOptions } from "@protobuf-ts/runtime-rpc";
|
||||
/**
|
||||
* Invoices is a service that can be used to create, accept, settle and cancel
|
||||
* invoices.
|
||||
*
|
||||
* @generated from protobuf service invoicesrpc.Invoices
|
||||
*/
|
||||
export interface IInvoicesClient {
|
||||
/**
|
||||
*
|
||||
* SubscribeSingleInvoice returns a uni-directional stream (server -> client)
|
||||
* to notify the client of state transitions of the specified invoice.
|
||||
* Initially the current invoice state is always sent out.
|
||||
*
|
||||
* @generated from protobuf rpc: SubscribeSingleInvoice(invoicesrpc.SubscribeSingleInvoiceRequest) returns (stream lnrpc.Invoice);
|
||||
*/
|
||||
subscribeSingleInvoice(input: SubscribeSingleInvoiceRequest, options?: RpcOptions): ServerStreamingCall<SubscribeSingleInvoiceRequest, Invoice>;
|
||||
/**
|
||||
*
|
||||
* CancelInvoice cancels a currently open invoice. If the invoice is already
|
||||
* canceled, this call will succeed. If the invoice is already settled, it will
|
||||
* fail.
|
||||
*
|
||||
* @generated from protobuf rpc: CancelInvoice(invoicesrpc.CancelInvoiceMsg) returns (invoicesrpc.CancelInvoiceResp);
|
||||
*/
|
||||
cancelInvoice(input: CancelInvoiceMsg, options?: RpcOptions): UnaryCall<CancelInvoiceMsg, CancelInvoiceResp>;
|
||||
/**
|
||||
*
|
||||
* AddHoldInvoice creates a hold invoice. It ties the invoice to the hash
|
||||
* supplied in the request.
|
||||
*
|
||||
* @generated from protobuf rpc: AddHoldInvoice(invoicesrpc.AddHoldInvoiceRequest) returns (invoicesrpc.AddHoldInvoiceResp);
|
||||
*/
|
||||
addHoldInvoice(input: AddHoldInvoiceRequest, options?: RpcOptions): UnaryCall<AddHoldInvoiceRequest, AddHoldInvoiceResp>;
|
||||
/**
|
||||
*
|
||||
* SettleInvoice settles an accepted invoice. If the invoice is already
|
||||
* settled, this call will succeed.
|
||||
*
|
||||
* @generated from protobuf rpc: SettleInvoice(invoicesrpc.SettleInvoiceMsg) returns (invoicesrpc.SettleInvoiceResp);
|
||||
*/
|
||||
settleInvoice(input: SettleInvoiceMsg, options?: RpcOptions): UnaryCall<SettleInvoiceMsg, SettleInvoiceResp>;
|
||||
/**
|
||||
*
|
||||
* LookupInvoiceV2 attempts to look up at invoice. An invoice can be refrenced
|
||||
* using either its payment hash, payment address, or set ID.
|
||||
*
|
||||
* @generated from protobuf rpc: LookupInvoiceV2(invoicesrpc.LookupInvoiceMsg) returns (lnrpc.Invoice);
|
||||
*/
|
||||
lookupInvoiceV2(input: LookupInvoiceMsg, options?: RpcOptions): UnaryCall<LookupInvoiceMsg, Invoice>;
|
||||
}
|
||||
/**
|
||||
* Invoices is a service that can be used to create, accept, settle and cancel
|
||||
* invoices.
|
||||
*
|
||||
* @generated from protobuf service invoicesrpc.Invoices
|
||||
*/
|
||||
export class InvoicesClient implements IInvoicesClient, ServiceInfo {
|
||||
typeName = Invoices.typeName;
|
||||
methods = Invoices.methods;
|
||||
options = Invoices.options;
|
||||
constructor(private readonly _transport: RpcTransport) {
|
||||
}
|
||||
/**
|
||||
*
|
||||
* SubscribeSingleInvoice returns a uni-directional stream (server -> client)
|
||||
* to notify the client of state transitions of the specified invoice.
|
||||
* Initially the current invoice state is always sent out.
|
||||
*
|
||||
* @generated from protobuf rpc: SubscribeSingleInvoice(invoicesrpc.SubscribeSingleInvoiceRequest) returns (stream lnrpc.Invoice);
|
||||
*/
|
||||
subscribeSingleInvoice(input: SubscribeSingleInvoiceRequest, options?: RpcOptions): ServerStreamingCall<SubscribeSingleInvoiceRequest, Invoice> {
|
||||
const method = this.methods[0], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<SubscribeSingleInvoiceRequest, Invoice>("serverStreaming", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* CancelInvoice cancels a currently open invoice. If the invoice is already
|
||||
* canceled, this call will succeed. If the invoice is already settled, it will
|
||||
* fail.
|
||||
*
|
||||
* @generated from protobuf rpc: CancelInvoice(invoicesrpc.CancelInvoiceMsg) returns (invoicesrpc.CancelInvoiceResp);
|
||||
*/
|
||||
cancelInvoice(input: CancelInvoiceMsg, options?: RpcOptions): UnaryCall<CancelInvoiceMsg, CancelInvoiceResp> {
|
||||
const method = this.methods[1], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<CancelInvoiceMsg, CancelInvoiceResp>("unary", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* AddHoldInvoice creates a hold invoice. It ties the invoice to the hash
|
||||
* supplied in the request.
|
||||
*
|
||||
* @generated from protobuf rpc: AddHoldInvoice(invoicesrpc.AddHoldInvoiceRequest) returns (invoicesrpc.AddHoldInvoiceResp);
|
||||
*/
|
||||
addHoldInvoice(input: AddHoldInvoiceRequest, options?: RpcOptions): UnaryCall<AddHoldInvoiceRequest, AddHoldInvoiceResp> {
|
||||
const method = this.methods[2], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<AddHoldInvoiceRequest, AddHoldInvoiceResp>("unary", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* SettleInvoice settles an accepted invoice. If the invoice is already
|
||||
* settled, this call will succeed.
|
||||
*
|
||||
* @generated from protobuf rpc: SettleInvoice(invoicesrpc.SettleInvoiceMsg) returns (invoicesrpc.SettleInvoiceResp);
|
||||
*/
|
||||
settleInvoice(input: SettleInvoiceMsg, options?: RpcOptions): UnaryCall<SettleInvoiceMsg, SettleInvoiceResp> {
|
||||
const method = this.methods[3], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<SettleInvoiceMsg, SettleInvoiceResp>("unary", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* LookupInvoiceV2 attempts to look up at invoice. An invoice can be refrenced
|
||||
* using either its payment hash, payment address, or set ID.
|
||||
*
|
||||
* @generated from protobuf rpc: LookupInvoiceV2(invoicesrpc.LookupInvoiceMsg) returns (lnrpc.Invoice);
|
||||
*/
|
||||
lookupInvoiceV2(input: LookupInvoiceMsg, options?: RpcOptions): UnaryCall<LookupInvoiceMsg, Invoice> {
|
||||
const method = this.methods[4], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<LookupInvoiceMsg, Invoice>("unary", this._transport, method, opt, input);
|
||||
}
|
||||
}
|
||||
690
proto/lnd/invoices.ts
Normal file
690
proto/lnd/invoices.ts
Normal file
|
|
@ -0,0 +1,690 @@
|
|||
// @generated by protobuf-ts 2.5.0
|
||||
// @generated from protobuf file "invoices.proto" (package "invoicesrpc", syntax proto3)
|
||||
// tslint:disable
|
||||
import { Invoice } from "./lightning";
|
||||
import { ServiceType } from "@protobuf-ts/runtime-rpc";
|
||||
import type { BinaryWriteOptions } from "@protobuf-ts/runtime";
|
||||
import type { IBinaryWriter } from "@protobuf-ts/runtime";
|
||||
import { WireType } from "@protobuf-ts/runtime";
|
||||
import type { BinaryReadOptions } from "@protobuf-ts/runtime";
|
||||
import type { IBinaryReader } from "@protobuf-ts/runtime";
|
||||
import { UnknownFieldHandler } from "@protobuf-ts/runtime";
|
||||
import type { PartialMessage } from "@protobuf-ts/runtime";
|
||||
import { reflectionMergePartial } from "@protobuf-ts/runtime";
|
||||
import { MESSAGE_TYPE } from "@protobuf-ts/runtime";
|
||||
import { MessageType } from "@protobuf-ts/runtime";
|
||||
import { RouteHint } from "./lightning";
|
||||
/**
|
||||
* @generated from protobuf message invoicesrpc.CancelInvoiceMsg
|
||||
*/
|
||||
export interface CancelInvoiceMsg {
|
||||
/**
|
||||
* Hash corresponding to the (hold) invoice to cancel. When using
|
||||
* REST, this field must be encoded as base64.
|
||||
*
|
||||
* @generated from protobuf field: bytes payment_hash = 1;
|
||||
*/
|
||||
paymentHash: Uint8Array;
|
||||
}
|
||||
/**
|
||||
* @generated from protobuf message invoicesrpc.CancelInvoiceResp
|
||||
*/
|
||||
export interface CancelInvoiceResp {
|
||||
}
|
||||
/**
|
||||
* @generated from protobuf message invoicesrpc.AddHoldInvoiceRequest
|
||||
*/
|
||||
export interface AddHoldInvoiceRequest {
|
||||
/**
|
||||
*
|
||||
* An optional memo to attach along with the invoice. Used for record keeping
|
||||
* purposes for the invoice's creator, and will also be set in the description
|
||||
* field of the encoded payment request if the description_hash field is not
|
||||
* being used.
|
||||
*
|
||||
* @generated from protobuf field: string memo = 1;
|
||||
*/
|
||||
memo: string;
|
||||
/**
|
||||
* The hash of the preimage
|
||||
*
|
||||
* @generated from protobuf field: bytes hash = 2;
|
||||
*/
|
||||
hash: Uint8Array;
|
||||
/**
|
||||
*
|
||||
* The value of this invoice in satoshis
|
||||
*
|
||||
* The fields value and value_msat are mutually exclusive.
|
||||
*
|
||||
* @generated from protobuf field: int64 value = 3;
|
||||
*/
|
||||
value: bigint;
|
||||
/**
|
||||
*
|
||||
* The value of this invoice in millisatoshis
|
||||
*
|
||||
* The fields value and value_msat are mutually exclusive.
|
||||
*
|
||||
* @generated from protobuf field: int64 value_msat = 10;
|
||||
*/
|
||||
valueMsat: bigint;
|
||||
/**
|
||||
*
|
||||
* Hash (SHA-256) of a description of the payment. Used if the description of
|
||||
* payment (memo) is too long to naturally fit within the description field
|
||||
* of an encoded payment request.
|
||||
*
|
||||
* @generated from protobuf field: bytes description_hash = 4;
|
||||
*/
|
||||
descriptionHash: Uint8Array;
|
||||
/**
|
||||
* Payment request expiry time in seconds. Default is 3600 (1 hour).
|
||||
*
|
||||
* @generated from protobuf field: int64 expiry = 5;
|
||||
*/
|
||||
expiry: bigint;
|
||||
/**
|
||||
* Fallback on-chain address.
|
||||
*
|
||||
* @generated from protobuf field: string fallback_addr = 6;
|
||||
*/
|
||||
fallbackAddr: string;
|
||||
/**
|
||||
* Delta to use for the time-lock of the CLTV extended to the final hop.
|
||||
*
|
||||
* @generated from protobuf field: uint64 cltv_expiry = 7;
|
||||
*/
|
||||
cltvExpiry: bigint;
|
||||
/**
|
||||
*
|
||||
* Route hints that can each be individually used to assist in reaching the
|
||||
* invoice's destination.
|
||||
*
|
||||
* @generated from protobuf field: repeated lnrpc.RouteHint route_hints = 8;
|
||||
*/
|
||||
routeHints: RouteHint[];
|
||||
/**
|
||||
* Whether this invoice should include routing hints for private channels.
|
||||
*
|
||||
* @generated from protobuf field: bool private = 9;
|
||||
*/
|
||||
private: boolean;
|
||||
}
|
||||
/**
|
||||
* @generated from protobuf message invoicesrpc.AddHoldInvoiceResp
|
||||
*/
|
||||
export interface AddHoldInvoiceResp {
|
||||
/**
|
||||
*
|
||||
* A bare-bones invoice for a payment within the Lightning Network. With the
|
||||
* details of the invoice, the sender has all the data necessary to send a
|
||||
* payment to the recipient.
|
||||
*
|
||||
* @generated from protobuf field: string payment_request = 1;
|
||||
*/
|
||||
paymentRequest: string;
|
||||
/**
|
||||
*
|
||||
* The "add" index of this invoice. Each newly created invoice will increment
|
||||
* this index making it monotonically increasing. Callers to the
|
||||
* SubscribeInvoices call can use this to instantly get notified of all added
|
||||
* invoices with an add_index greater than this one.
|
||||
*
|
||||
* @generated from protobuf field: uint64 add_index = 2;
|
||||
*/
|
||||
addIndex: bigint;
|
||||
/**
|
||||
*
|
||||
* The payment address of the generated invoice. This value should be used
|
||||
* in all payments for this invoice as we require it for end to end
|
||||
* security.
|
||||
*
|
||||
* @generated from protobuf field: bytes payment_addr = 3;
|
||||
*/
|
||||
paymentAddr: Uint8Array;
|
||||
}
|
||||
/**
|
||||
* @generated from protobuf message invoicesrpc.SettleInvoiceMsg
|
||||
*/
|
||||
export interface SettleInvoiceMsg {
|
||||
/**
|
||||
* Externally discovered pre-image that should be used to settle the hold
|
||||
* invoice.
|
||||
*
|
||||
* @generated from protobuf field: bytes preimage = 1;
|
||||
*/
|
||||
preimage: Uint8Array;
|
||||
}
|
||||
/**
|
||||
* @generated from protobuf message invoicesrpc.SettleInvoiceResp
|
||||
*/
|
||||
export interface SettleInvoiceResp {
|
||||
}
|
||||
/**
|
||||
* @generated from protobuf message invoicesrpc.SubscribeSingleInvoiceRequest
|
||||
*/
|
||||
export interface SubscribeSingleInvoiceRequest {
|
||||
/**
|
||||
* Hash corresponding to the (hold) invoice to subscribe to. When using
|
||||
* REST, this field must be encoded as base64url.
|
||||
*
|
||||
* @generated from protobuf field: bytes r_hash = 2;
|
||||
*/
|
||||
rHash: Uint8Array;
|
||||
}
|
||||
/**
|
||||
* @generated from protobuf message invoicesrpc.LookupInvoiceMsg
|
||||
*/
|
||||
export interface LookupInvoiceMsg {
|
||||
/**
|
||||
* @generated from protobuf oneof: invoice_ref
|
||||
*/
|
||||
invoiceRef: {
|
||||
oneofKind: "paymentHash";
|
||||
/**
|
||||
* When using REST, this field must be encoded as base64.
|
||||
*
|
||||
* @generated from protobuf field: bytes payment_hash = 1;
|
||||
*/
|
||||
paymentHash: Uint8Array;
|
||||
} | {
|
||||
oneofKind: "paymentAddr";
|
||||
/**
|
||||
* @generated from protobuf field: bytes payment_addr = 2;
|
||||
*/
|
||||
paymentAddr: Uint8Array;
|
||||
} | {
|
||||
oneofKind: "setId";
|
||||
/**
|
||||
* @generated from protobuf field: bytes set_id = 3;
|
||||
*/
|
||||
setId: Uint8Array;
|
||||
} | {
|
||||
oneofKind: undefined;
|
||||
};
|
||||
/**
|
||||
* @generated from protobuf field: invoicesrpc.LookupModifier lookup_modifier = 4;
|
||||
*/
|
||||
lookupModifier: LookupModifier;
|
||||
}
|
||||
/**
|
||||
* @generated from protobuf enum invoicesrpc.LookupModifier
|
||||
*/
|
||||
export enum LookupModifier {
|
||||
/**
|
||||
* The default look up modifier, no look up behavior is changed.
|
||||
*
|
||||
* @generated from protobuf enum value: DEFAULT = 0;
|
||||
*/
|
||||
DEFAULT = 0,
|
||||
/**
|
||||
*
|
||||
* Indicates that when a look up is done based on a set_id, then only that set
|
||||
* of HTLCs related to that set ID should be returned.
|
||||
*
|
||||
* @generated from protobuf enum value: HTLC_SET_ONLY = 1;
|
||||
*/
|
||||
HTLC_SET_ONLY = 1,
|
||||
/**
|
||||
*
|
||||
* Indicates that when a look up is done using a payment_addr, then no HTLCs
|
||||
* related to the payment_addr should be returned. This is useful when one
|
||||
* wants to be able to obtain the set of associated setIDs with a given
|
||||
* invoice, then look up the sub-invoices "projected" by that set ID.
|
||||
*
|
||||
* @generated from protobuf enum value: HTLC_SET_BLANK = 2;
|
||||
*/
|
||||
HTLC_SET_BLANK = 2
|
||||
}
|
||||
// @generated message type with reflection information, may provide speed optimized methods
|
||||
class CancelInvoiceMsg$Type extends MessageType<CancelInvoiceMsg> {
|
||||
constructor() {
|
||||
super("invoicesrpc.CancelInvoiceMsg", [
|
||||
{ no: 1, name: "payment_hash", kind: "scalar", T: 12 /*ScalarType.BYTES*/ }
|
||||
]);
|
||||
}
|
||||
create(value?: PartialMessage<CancelInvoiceMsg>): CancelInvoiceMsg {
|
||||
const message = { paymentHash: new Uint8Array(0) };
|
||||
globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
|
||||
if (value !== undefined)
|
||||
reflectionMergePartial<CancelInvoiceMsg>(this, message, value);
|
||||
return message;
|
||||
}
|
||||
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: CancelInvoiceMsg): CancelInvoiceMsg {
|
||||
let message = target ?? this.create(), end = reader.pos + length;
|
||||
while (reader.pos < end) {
|
||||
let [fieldNo, wireType] = reader.tag();
|
||||
switch (fieldNo) {
|
||||
case /* bytes payment_hash */ 1:
|
||||
message.paymentHash = reader.bytes();
|
||||
break;
|
||||
default:
|
||||
let u = options.readUnknownField;
|
||||
if (u === "throw")
|
||||
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
|
||||
let d = reader.skip(wireType);
|
||||
if (u !== false)
|
||||
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
|
||||
}
|
||||
}
|
||||
return message;
|
||||
}
|
||||
internalBinaryWrite(message: CancelInvoiceMsg, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
|
||||
/* bytes payment_hash = 1; */
|
||||
if (message.paymentHash.length)
|
||||
writer.tag(1, WireType.LengthDelimited).bytes(message.paymentHash);
|
||||
let u = options.writeUnknownFields;
|
||||
if (u !== false)
|
||||
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
|
||||
return writer;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @generated MessageType for protobuf message invoicesrpc.CancelInvoiceMsg
|
||||
*/
|
||||
export const CancelInvoiceMsg = new CancelInvoiceMsg$Type();
|
||||
// @generated message type with reflection information, may provide speed optimized methods
|
||||
class CancelInvoiceResp$Type extends MessageType<CancelInvoiceResp> {
|
||||
constructor() {
|
||||
super("invoicesrpc.CancelInvoiceResp", []);
|
||||
}
|
||||
create(value?: PartialMessage<CancelInvoiceResp>): CancelInvoiceResp {
|
||||
const message = {};
|
||||
globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
|
||||
if (value !== undefined)
|
||||
reflectionMergePartial<CancelInvoiceResp>(this, message, value);
|
||||
return message;
|
||||
}
|
||||
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: CancelInvoiceResp): CancelInvoiceResp {
|
||||
return target ?? this.create();
|
||||
}
|
||||
internalBinaryWrite(message: CancelInvoiceResp, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
|
||||
let u = options.writeUnknownFields;
|
||||
if (u !== false)
|
||||
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
|
||||
return writer;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @generated MessageType for protobuf message invoicesrpc.CancelInvoiceResp
|
||||
*/
|
||||
export const CancelInvoiceResp = new CancelInvoiceResp$Type();
|
||||
// @generated message type with reflection information, may provide speed optimized methods
|
||||
class AddHoldInvoiceRequest$Type extends MessageType<AddHoldInvoiceRequest> {
|
||||
constructor() {
|
||||
super("invoicesrpc.AddHoldInvoiceRequest", [
|
||||
{ no: 1, name: "memo", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
|
||||
{ no: 2, name: "hash", kind: "scalar", T: 12 /*ScalarType.BYTES*/ },
|
||||
{ no: 3, name: "value", kind: "scalar", T: 3 /*ScalarType.INT64*/, L: 0 /*LongType.BIGINT*/ },
|
||||
{ no: 10, name: "value_msat", kind: "scalar", T: 3 /*ScalarType.INT64*/, L: 0 /*LongType.BIGINT*/ },
|
||||
{ no: 4, name: "description_hash", kind: "scalar", T: 12 /*ScalarType.BYTES*/ },
|
||||
{ no: 5, name: "expiry", kind: "scalar", T: 3 /*ScalarType.INT64*/, L: 0 /*LongType.BIGINT*/ },
|
||||
{ no: 6, name: "fallback_addr", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
|
||||
{ no: 7, name: "cltv_expiry", kind: "scalar", T: 4 /*ScalarType.UINT64*/, L: 0 /*LongType.BIGINT*/ },
|
||||
{ no: 8, name: "route_hints", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => RouteHint },
|
||||
{ no: 9, name: "private", kind: "scalar", T: 8 /*ScalarType.BOOL*/ }
|
||||
]);
|
||||
}
|
||||
create(value?: PartialMessage<AddHoldInvoiceRequest>): AddHoldInvoiceRequest {
|
||||
const message = { memo: "", hash: new Uint8Array(0), value: 0n, valueMsat: 0n, descriptionHash: new Uint8Array(0), expiry: 0n, fallbackAddr: "", cltvExpiry: 0n, routeHints: [], private: false };
|
||||
globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
|
||||
if (value !== undefined)
|
||||
reflectionMergePartial<AddHoldInvoiceRequest>(this, message, value);
|
||||
return message;
|
||||
}
|
||||
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: AddHoldInvoiceRequest): AddHoldInvoiceRequest {
|
||||
let message = target ?? this.create(), end = reader.pos + length;
|
||||
while (reader.pos < end) {
|
||||
let [fieldNo, wireType] = reader.tag();
|
||||
switch (fieldNo) {
|
||||
case /* string memo */ 1:
|
||||
message.memo = reader.string();
|
||||
break;
|
||||
case /* bytes hash */ 2:
|
||||
message.hash = reader.bytes();
|
||||
break;
|
||||
case /* int64 value */ 3:
|
||||
message.value = reader.int64().toBigInt();
|
||||
break;
|
||||
case /* int64 value_msat */ 10:
|
||||
message.valueMsat = reader.int64().toBigInt();
|
||||
break;
|
||||
case /* bytes description_hash */ 4:
|
||||
message.descriptionHash = reader.bytes();
|
||||
break;
|
||||
case /* int64 expiry */ 5:
|
||||
message.expiry = reader.int64().toBigInt();
|
||||
break;
|
||||
case /* string fallback_addr */ 6:
|
||||
message.fallbackAddr = reader.string();
|
||||
break;
|
||||
case /* uint64 cltv_expiry */ 7:
|
||||
message.cltvExpiry = reader.uint64().toBigInt();
|
||||
break;
|
||||
case /* repeated lnrpc.RouteHint route_hints */ 8:
|
||||
message.routeHints.push(RouteHint.internalBinaryRead(reader, reader.uint32(), options));
|
||||
break;
|
||||
case /* bool private */ 9:
|
||||
message.private = reader.bool();
|
||||
break;
|
||||
default:
|
||||
let u = options.readUnknownField;
|
||||
if (u === "throw")
|
||||
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
|
||||
let d = reader.skip(wireType);
|
||||
if (u !== false)
|
||||
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
|
||||
}
|
||||
}
|
||||
return message;
|
||||
}
|
||||
internalBinaryWrite(message: AddHoldInvoiceRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
|
||||
/* string memo = 1; */
|
||||
if (message.memo !== "")
|
||||
writer.tag(1, WireType.LengthDelimited).string(message.memo);
|
||||
/* bytes hash = 2; */
|
||||
if (message.hash.length)
|
||||
writer.tag(2, WireType.LengthDelimited).bytes(message.hash);
|
||||
/* int64 value = 3; */
|
||||
if (message.value !== 0n)
|
||||
writer.tag(3, WireType.Varint).int64(message.value);
|
||||
/* int64 value_msat = 10; */
|
||||
if (message.valueMsat !== 0n)
|
||||
writer.tag(10, WireType.Varint).int64(message.valueMsat);
|
||||
/* bytes description_hash = 4; */
|
||||
if (message.descriptionHash.length)
|
||||
writer.tag(4, WireType.LengthDelimited).bytes(message.descriptionHash);
|
||||
/* int64 expiry = 5; */
|
||||
if (message.expiry !== 0n)
|
||||
writer.tag(5, WireType.Varint).int64(message.expiry);
|
||||
/* string fallback_addr = 6; */
|
||||
if (message.fallbackAddr !== "")
|
||||
writer.tag(6, WireType.LengthDelimited).string(message.fallbackAddr);
|
||||
/* uint64 cltv_expiry = 7; */
|
||||
if (message.cltvExpiry !== 0n)
|
||||
writer.tag(7, WireType.Varint).uint64(message.cltvExpiry);
|
||||
/* repeated lnrpc.RouteHint route_hints = 8; */
|
||||
for (let i = 0; i < message.routeHints.length; i++)
|
||||
RouteHint.internalBinaryWrite(message.routeHints[i], writer.tag(8, WireType.LengthDelimited).fork(), options).join();
|
||||
/* bool private = 9; */
|
||||
if (message.private !== false)
|
||||
writer.tag(9, WireType.Varint).bool(message.private);
|
||||
let u = options.writeUnknownFields;
|
||||
if (u !== false)
|
||||
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
|
||||
return writer;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @generated MessageType for protobuf message invoicesrpc.AddHoldInvoiceRequest
|
||||
*/
|
||||
export const AddHoldInvoiceRequest = new AddHoldInvoiceRequest$Type();
|
||||
// @generated message type with reflection information, may provide speed optimized methods
|
||||
class AddHoldInvoiceResp$Type extends MessageType<AddHoldInvoiceResp> {
|
||||
constructor() {
|
||||
super("invoicesrpc.AddHoldInvoiceResp", [
|
||||
{ no: 1, name: "payment_request", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
|
||||
{ no: 2, name: "add_index", kind: "scalar", T: 4 /*ScalarType.UINT64*/, L: 0 /*LongType.BIGINT*/ },
|
||||
{ no: 3, name: "payment_addr", kind: "scalar", T: 12 /*ScalarType.BYTES*/ }
|
||||
]);
|
||||
}
|
||||
create(value?: PartialMessage<AddHoldInvoiceResp>): AddHoldInvoiceResp {
|
||||
const message = { paymentRequest: "", addIndex: 0n, paymentAddr: new Uint8Array(0) };
|
||||
globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
|
||||
if (value !== undefined)
|
||||
reflectionMergePartial<AddHoldInvoiceResp>(this, message, value);
|
||||
return message;
|
||||
}
|
||||
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: AddHoldInvoiceResp): AddHoldInvoiceResp {
|
||||
let message = target ?? this.create(), end = reader.pos + length;
|
||||
while (reader.pos < end) {
|
||||
let [fieldNo, wireType] = reader.tag();
|
||||
switch (fieldNo) {
|
||||
case /* string payment_request */ 1:
|
||||
message.paymentRequest = reader.string();
|
||||
break;
|
||||
case /* uint64 add_index */ 2:
|
||||
message.addIndex = reader.uint64().toBigInt();
|
||||
break;
|
||||
case /* bytes payment_addr */ 3:
|
||||
message.paymentAddr = reader.bytes();
|
||||
break;
|
||||
default:
|
||||
let u = options.readUnknownField;
|
||||
if (u === "throw")
|
||||
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
|
||||
let d = reader.skip(wireType);
|
||||
if (u !== false)
|
||||
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
|
||||
}
|
||||
}
|
||||
return message;
|
||||
}
|
||||
internalBinaryWrite(message: AddHoldInvoiceResp, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
|
||||
/* string payment_request = 1; */
|
||||
if (message.paymentRequest !== "")
|
||||
writer.tag(1, WireType.LengthDelimited).string(message.paymentRequest);
|
||||
/* uint64 add_index = 2; */
|
||||
if (message.addIndex !== 0n)
|
||||
writer.tag(2, WireType.Varint).uint64(message.addIndex);
|
||||
/* bytes payment_addr = 3; */
|
||||
if (message.paymentAddr.length)
|
||||
writer.tag(3, WireType.LengthDelimited).bytes(message.paymentAddr);
|
||||
let u = options.writeUnknownFields;
|
||||
if (u !== false)
|
||||
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
|
||||
return writer;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @generated MessageType for protobuf message invoicesrpc.AddHoldInvoiceResp
|
||||
*/
|
||||
export const AddHoldInvoiceResp = new AddHoldInvoiceResp$Type();
|
||||
// @generated message type with reflection information, may provide speed optimized methods
|
||||
class SettleInvoiceMsg$Type extends MessageType<SettleInvoiceMsg> {
|
||||
constructor() {
|
||||
super("invoicesrpc.SettleInvoiceMsg", [
|
||||
{ no: 1, name: "preimage", kind: "scalar", T: 12 /*ScalarType.BYTES*/ }
|
||||
]);
|
||||
}
|
||||
create(value?: PartialMessage<SettleInvoiceMsg>): SettleInvoiceMsg {
|
||||
const message = { preimage: new Uint8Array(0) };
|
||||
globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
|
||||
if (value !== undefined)
|
||||
reflectionMergePartial<SettleInvoiceMsg>(this, message, value);
|
||||
return message;
|
||||
}
|
||||
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: SettleInvoiceMsg): SettleInvoiceMsg {
|
||||
let message = target ?? this.create(), end = reader.pos + length;
|
||||
while (reader.pos < end) {
|
||||
let [fieldNo, wireType] = reader.tag();
|
||||
switch (fieldNo) {
|
||||
case /* bytes preimage */ 1:
|
||||
message.preimage = reader.bytes();
|
||||
break;
|
||||
default:
|
||||
let u = options.readUnknownField;
|
||||
if (u === "throw")
|
||||
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
|
||||
let d = reader.skip(wireType);
|
||||
if (u !== false)
|
||||
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
|
||||
}
|
||||
}
|
||||
return message;
|
||||
}
|
||||
internalBinaryWrite(message: SettleInvoiceMsg, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
|
||||
/* bytes preimage = 1; */
|
||||
if (message.preimage.length)
|
||||
writer.tag(1, WireType.LengthDelimited).bytes(message.preimage);
|
||||
let u = options.writeUnknownFields;
|
||||
if (u !== false)
|
||||
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
|
||||
return writer;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @generated MessageType for protobuf message invoicesrpc.SettleInvoiceMsg
|
||||
*/
|
||||
export const SettleInvoiceMsg = new SettleInvoiceMsg$Type();
|
||||
// @generated message type with reflection information, may provide speed optimized methods
|
||||
class SettleInvoiceResp$Type extends MessageType<SettleInvoiceResp> {
|
||||
constructor() {
|
||||
super("invoicesrpc.SettleInvoiceResp", []);
|
||||
}
|
||||
create(value?: PartialMessage<SettleInvoiceResp>): SettleInvoiceResp {
|
||||
const message = {};
|
||||
globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
|
||||
if (value !== undefined)
|
||||
reflectionMergePartial<SettleInvoiceResp>(this, message, value);
|
||||
return message;
|
||||
}
|
||||
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: SettleInvoiceResp): SettleInvoiceResp {
|
||||
return target ?? this.create();
|
||||
}
|
||||
internalBinaryWrite(message: SettleInvoiceResp, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
|
||||
let u = options.writeUnknownFields;
|
||||
if (u !== false)
|
||||
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
|
||||
return writer;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @generated MessageType for protobuf message invoicesrpc.SettleInvoiceResp
|
||||
*/
|
||||
export const SettleInvoiceResp = new SettleInvoiceResp$Type();
|
||||
// @generated message type with reflection information, may provide speed optimized methods
|
||||
class SubscribeSingleInvoiceRequest$Type extends MessageType<SubscribeSingleInvoiceRequest> {
|
||||
constructor() {
|
||||
super("invoicesrpc.SubscribeSingleInvoiceRequest", [
|
||||
{ no: 2, name: "r_hash", kind: "scalar", T: 12 /*ScalarType.BYTES*/ }
|
||||
]);
|
||||
}
|
||||
create(value?: PartialMessage<SubscribeSingleInvoiceRequest>): SubscribeSingleInvoiceRequest {
|
||||
const message = { rHash: new Uint8Array(0) };
|
||||
globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
|
||||
if (value !== undefined)
|
||||
reflectionMergePartial<SubscribeSingleInvoiceRequest>(this, message, value);
|
||||
return message;
|
||||
}
|
||||
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: SubscribeSingleInvoiceRequest): SubscribeSingleInvoiceRequest {
|
||||
let message = target ?? this.create(), end = reader.pos + length;
|
||||
while (reader.pos < end) {
|
||||
let [fieldNo, wireType] = reader.tag();
|
||||
switch (fieldNo) {
|
||||
case /* bytes r_hash */ 2:
|
||||
message.rHash = reader.bytes();
|
||||
break;
|
||||
default:
|
||||
let u = options.readUnknownField;
|
||||
if (u === "throw")
|
||||
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
|
||||
let d = reader.skip(wireType);
|
||||
if (u !== false)
|
||||
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
|
||||
}
|
||||
}
|
||||
return message;
|
||||
}
|
||||
internalBinaryWrite(message: SubscribeSingleInvoiceRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
|
||||
/* bytes r_hash = 2; */
|
||||
if (message.rHash.length)
|
||||
writer.tag(2, WireType.LengthDelimited).bytes(message.rHash);
|
||||
let u = options.writeUnknownFields;
|
||||
if (u !== false)
|
||||
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
|
||||
return writer;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @generated MessageType for protobuf message invoicesrpc.SubscribeSingleInvoiceRequest
|
||||
*/
|
||||
export const SubscribeSingleInvoiceRequest = new SubscribeSingleInvoiceRequest$Type();
|
||||
// @generated message type with reflection information, may provide speed optimized methods
|
||||
class LookupInvoiceMsg$Type extends MessageType<LookupInvoiceMsg> {
|
||||
constructor() {
|
||||
super("invoicesrpc.LookupInvoiceMsg", [
|
||||
{ no: 1, name: "payment_hash", kind: "scalar", oneof: "invoiceRef", T: 12 /*ScalarType.BYTES*/ },
|
||||
{ no: 2, name: "payment_addr", kind: "scalar", oneof: "invoiceRef", T: 12 /*ScalarType.BYTES*/ },
|
||||
{ no: 3, name: "set_id", kind: "scalar", oneof: "invoiceRef", T: 12 /*ScalarType.BYTES*/ },
|
||||
{ no: 4, name: "lookup_modifier", kind: "enum", T: () => ["invoicesrpc.LookupModifier", LookupModifier] }
|
||||
]);
|
||||
}
|
||||
create(value?: PartialMessage<LookupInvoiceMsg>): LookupInvoiceMsg {
|
||||
const message = { invoiceRef: { oneofKind: undefined }, lookupModifier: 0 };
|
||||
globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
|
||||
if (value !== undefined)
|
||||
reflectionMergePartial<LookupInvoiceMsg>(this, message, value);
|
||||
return message;
|
||||
}
|
||||
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: LookupInvoiceMsg): LookupInvoiceMsg {
|
||||
let message = target ?? this.create(), end = reader.pos + length;
|
||||
while (reader.pos < end) {
|
||||
let [fieldNo, wireType] = reader.tag();
|
||||
switch (fieldNo) {
|
||||
case /* bytes payment_hash */ 1:
|
||||
message.invoiceRef = {
|
||||
oneofKind: "paymentHash",
|
||||
paymentHash: reader.bytes()
|
||||
};
|
||||
break;
|
||||
case /* bytes payment_addr */ 2:
|
||||
message.invoiceRef = {
|
||||
oneofKind: "paymentAddr",
|
||||
paymentAddr: reader.bytes()
|
||||
};
|
||||
break;
|
||||
case /* bytes set_id */ 3:
|
||||
message.invoiceRef = {
|
||||
oneofKind: "setId",
|
||||
setId: reader.bytes()
|
||||
};
|
||||
break;
|
||||
case /* invoicesrpc.LookupModifier lookup_modifier */ 4:
|
||||
message.lookupModifier = reader.int32();
|
||||
break;
|
||||
default:
|
||||
let u = options.readUnknownField;
|
||||
if (u === "throw")
|
||||
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
|
||||
let d = reader.skip(wireType);
|
||||
if (u !== false)
|
||||
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
|
||||
}
|
||||
}
|
||||
return message;
|
||||
}
|
||||
internalBinaryWrite(message: LookupInvoiceMsg, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
|
||||
/* bytes payment_hash = 1; */
|
||||
if (message.invoiceRef.oneofKind === "paymentHash")
|
||||
writer.tag(1, WireType.LengthDelimited).bytes(message.invoiceRef.paymentHash);
|
||||
/* bytes payment_addr = 2; */
|
||||
if (message.invoiceRef.oneofKind === "paymentAddr")
|
||||
writer.tag(2, WireType.LengthDelimited).bytes(message.invoiceRef.paymentAddr);
|
||||
/* bytes set_id = 3; */
|
||||
if (message.invoiceRef.oneofKind === "setId")
|
||||
writer.tag(3, WireType.LengthDelimited).bytes(message.invoiceRef.setId);
|
||||
/* invoicesrpc.LookupModifier lookup_modifier = 4; */
|
||||
if (message.lookupModifier !== 0)
|
||||
writer.tag(4, WireType.Varint).int32(message.lookupModifier);
|
||||
let u = options.writeUnknownFields;
|
||||
if (u !== false)
|
||||
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
|
||||
return writer;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @generated MessageType for protobuf message invoicesrpc.LookupInvoiceMsg
|
||||
*/
|
||||
export const LookupInvoiceMsg = new LookupInvoiceMsg$Type();
|
||||
/**
|
||||
* @generated ServiceType for protobuf service invoicesrpc.Invoices
|
||||
*/
|
||||
export const Invoices = new ServiceType("invoicesrpc.Invoices", [
|
||||
{ name: "SubscribeSingleInvoice", serverStreaming: true, options: {}, I: SubscribeSingleInvoiceRequest, O: Invoice },
|
||||
{ name: "CancelInvoice", options: {}, I: CancelInvoiceMsg, O: CancelInvoiceResp },
|
||||
{ name: "AddHoldInvoice", options: {}, I: AddHoldInvoiceRequest, O: AddHoldInvoiceResp },
|
||||
{ name: "SettleInvoice", options: {}, I: SettleInvoiceMsg, O: SettleInvoiceResp },
|
||||
{ name: "LookupInvoiceV2", options: {}, I: LookupInvoiceMsg, O: Invoice }
|
||||
]);
|
||||
1722
proto/lnd/lightning.client.ts
Normal file
1722
proto/lnd/lightning.client.ts
Normal file
File diff suppressed because it is too large
Load diff
20995
proto/lnd/lightning.ts
Normal file
20995
proto/lnd/lightning.ts
Normal file
File diff suppressed because it is too large
Load diff
446
proto/lnd/router.client.ts
Normal file
446
proto/lnd/router.client.ts
Normal file
|
|
@ -0,0 +1,446 @@
|
|||
// @generated by protobuf-ts 2.5.0
|
||||
// @generated from protobuf file "router.proto" (package "routerrpc", syntax proto3)
|
||||
// tslint:disable
|
||||
import type { RpcTransport } from "@protobuf-ts/runtime-rpc";
|
||||
import type { ServiceInfo } from "@protobuf-ts/runtime-rpc";
|
||||
import { Router } from "./router";
|
||||
import type { UpdateChanStatusResponse } from "./router";
|
||||
import type { UpdateChanStatusRequest } from "./router";
|
||||
import type { ForwardHtlcInterceptRequest } from "./router";
|
||||
import type { ForwardHtlcInterceptResponse } from "./router";
|
||||
import type { DuplexStreamingCall } from "@protobuf-ts/runtime-rpc";
|
||||
import type { PaymentStatus } from "./router";
|
||||
import type { HtlcEvent } from "./router";
|
||||
import type { SubscribeHtlcEventsRequest } from "./router";
|
||||
import type { BuildRouteResponse } from "./router";
|
||||
import type { BuildRouteRequest } from "./router";
|
||||
import type { QueryProbabilityResponse } from "./router";
|
||||
import type { QueryProbabilityRequest } from "./router";
|
||||
import type { SetMissionControlConfigResponse } from "./router";
|
||||
import type { SetMissionControlConfigRequest } from "./router";
|
||||
import type { GetMissionControlConfigResponse } from "./router";
|
||||
import type { GetMissionControlConfigRequest } from "./router";
|
||||
import type { XImportMissionControlResponse } from "./router";
|
||||
import type { XImportMissionControlRequest } from "./router";
|
||||
import type { QueryMissionControlResponse } from "./router";
|
||||
import type { QueryMissionControlRequest } from "./router";
|
||||
import type { ResetMissionControlResponse } from "./router";
|
||||
import type { ResetMissionControlRequest } from "./router";
|
||||
import type { HTLCAttempt } from "./lightning";
|
||||
import type { SendToRouteResponse } from "./router";
|
||||
import type { SendToRouteRequest } from "./router";
|
||||
import type { RouteFeeResponse } from "./router";
|
||||
import type { RouteFeeRequest } from "./router";
|
||||
import type { UnaryCall } from "@protobuf-ts/runtime-rpc";
|
||||
import type { TrackPaymentsRequest } from "./router";
|
||||
import type { TrackPaymentRequest } from "./router";
|
||||
import { stackIntercept } from "@protobuf-ts/runtime-rpc";
|
||||
import type { Payment } from "./lightning";
|
||||
import type { SendPaymentRequest } from "./router";
|
||||
import type { ServerStreamingCall } from "@protobuf-ts/runtime-rpc";
|
||||
import type { RpcOptions } from "@protobuf-ts/runtime-rpc";
|
||||
/**
|
||||
* Router is a service that offers advanced interaction with the router
|
||||
* subsystem of the daemon.
|
||||
*
|
||||
* @generated from protobuf service routerrpc.Router
|
||||
*/
|
||||
export interface IRouterClient {
|
||||
/**
|
||||
*
|
||||
* SendPaymentV2 attempts to route a payment described by the passed
|
||||
* PaymentRequest to the final destination. The call returns a stream of
|
||||
* payment updates.
|
||||
*
|
||||
* @generated from protobuf rpc: SendPaymentV2(routerrpc.SendPaymentRequest) returns (stream lnrpc.Payment);
|
||||
*/
|
||||
sendPaymentV2(input: SendPaymentRequest, options?: RpcOptions): ServerStreamingCall<SendPaymentRequest, Payment>;
|
||||
/**
|
||||
*
|
||||
* TrackPaymentV2 returns an update stream for the payment identified by the
|
||||
* payment hash.
|
||||
*
|
||||
* @generated from protobuf rpc: TrackPaymentV2(routerrpc.TrackPaymentRequest) returns (stream lnrpc.Payment);
|
||||
*/
|
||||
trackPaymentV2(input: TrackPaymentRequest, options?: RpcOptions): ServerStreamingCall<TrackPaymentRequest, Payment>;
|
||||
/**
|
||||
*
|
||||
* TrackPayments returns an update stream for every payment that is not in a
|
||||
* terminal state. Note that if payments are in-flight while starting a new
|
||||
* subscription, the start of the payment stream could produce out-of-order
|
||||
* and/or duplicate events. In order to get updates for every in-flight
|
||||
* payment attempt make sure to subscribe to this method before initiating any
|
||||
* payments.
|
||||
*
|
||||
* @generated from protobuf rpc: TrackPayments(routerrpc.TrackPaymentsRequest) returns (stream lnrpc.Payment);
|
||||
*/
|
||||
trackPayments(input: TrackPaymentsRequest, options?: RpcOptions): ServerStreamingCall<TrackPaymentsRequest, Payment>;
|
||||
/**
|
||||
*
|
||||
* EstimateRouteFee allows callers to obtain a lower bound w.r.t how much it
|
||||
* may cost to send an HTLC to the target end destination.
|
||||
*
|
||||
* @generated from protobuf rpc: EstimateRouteFee(routerrpc.RouteFeeRequest) returns (routerrpc.RouteFeeResponse);
|
||||
*/
|
||||
estimateRouteFee(input: RouteFeeRequest, options?: RpcOptions): UnaryCall<RouteFeeRequest, RouteFeeResponse>;
|
||||
/**
|
||||
*
|
||||
* Deprecated, use SendToRouteV2. SendToRoute attempts to make a payment via
|
||||
* the specified route. This method differs from SendPayment in that it
|
||||
* allows users to specify a full route manually. This can be used for
|
||||
* things like rebalancing, and atomic swaps. It differs from the newer
|
||||
* SendToRouteV2 in that it doesn't return the full HTLC information.
|
||||
*
|
||||
* @deprecated
|
||||
* @generated from protobuf rpc: SendToRoute(routerrpc.SendToRouteRequest) returns (routerrpc.SendToRouteResponse);
|
||||
*/
|
||||
sendToRoute(input: SendToRouteRequest, options?: RpcOptions): UnaryCall<SendToRouteRequest, SendToRouteResponse>;
|
||||
/**
|
||||
*
|
||||
* SendToRouteV2 attempts to make a payment via the specified route. This
|
||||
* method differs from SendPayment in that it allows users to specify a full
|
||||
* route manually. This can be used for things like rebalancing, and atomic
|
||||
* swaps.
|
||||
*
|
||||
* @generated from protobuf rpc: SendToRouteV2(routerrpc.SendToRouteRequest) returns (lnrpc.HTLCAttempt);
|
||||
*/
|
||||
sendToRouteV2(input: SendToRouteRequest, options?: RpcOptions): UnaryCall<SendToRouteRequest, HTLCAttempt>;
|
||||
/**
|
||||
*
|
||||
* ResetMissionControl clears all mission control state and starts with a clean
|
||||
* slate.
|
||||
*
|
||||
* @generated from protobuf rpc: ResetMissionControl(routerrpc.ResetMissionControlRequest) returns (routerrpc.ResetMissionControlResponse);
|
||||
*/
|
||||
resetMissionControl(input: ResetMissionControlRequest, options?: RpcOptions): UnaryCall<ResetMissionControlRequest, ResetMissionControlResponse>;
|
||||
/**
|
||||
*
|
||||
* QueryMissionControl exposes the internal mission control state to callers.
|
||||
* It is a development feature.
|
||||
*
|
||||
* @generated from protobuf rpc: QueryMissionControl(routerrpc.QueryMissionControlRequest) returns (routerrpc.QueryMissionControlResponse);
|
||||
*/
|
||||
queryMissionControl(input: QueryMissionControlRequest, options?: RpcOptions): UnaryCall<QueryMissionControlRequest, QueryMissionControlResponse>;
|
||||
/**
|
||||
*
|
||||
* XImportMissionControl is an experimental API that imports the state provided
|
||||
* to the internal mission control's state, using all results which are more
|
||||
* recent than our existing values. These values will only be imported
|
||||
* in-memory, and will not be persisted across restarts.
|
||||
*
|
||||
* @generated from protobuf rpc: XImportMissionControl(routerrpc.XImportMissionControlRequest) returns (routerrpc.XImportMissionControlResponse);
|
||||
*/
|
||||
xImportMissionControl(input: XImportMissionControlRequest, options?: RpcOptions): UnaryCall<XImportMissionControlRequest, XImportMissionControlResponse>;
|
||||
/**
|
||||
*
|
||||
* GetMissionControlConfig returns mission control's current config.
|
||||
*
|
||||
* @generated from protobuf rpc: GetMissionControlConfig(routerrpc.GetMissionControlConfigRequest) returns (routerrpc.GetMissionControlConfigResponse);
|
||||
*/
|
||||
getMissionControlConfig(input: GetMissionControlConfigRequest, options?: RpcOptions): UnaryCall<GetMissionControlConfigRequest, GetMissionControlConfigResponse>;
|
||||
/**
|
||||
*
|
||||
* SetMissionControlConfig will set mission control's config, if the config
|
||||
* provided is valid.
|
||||
*
|
||||
* @generated from protobuf rpc: SetMissionControlConfig(routerrpc.SetMissionControlConfigRequest) returns (routerrpc.SetMissionControlConfigResponse);
|
||||
*/
|
||||
setMissionControlConfig(input: SetMissionControlConfigRequest, options?: RpcOptions): UnaryCall<SetMissionControlConfigRequest, SetMissionControlConfigResponse>;
|
||||
/**
|
||||
*
|
||||
* QueryProbability returns the current success probability estimate for a
|
||||
* given node pair and amount.
|
||||
*
|
||||
* @generated from protobuf rpc: QueryProbability(routerrpc.QueryProbabilityRequest) returns (routerrpc.QueryProbabilityResponse);
|
||||
*/
|
||||
queryProbability(input: QueryProbabilityRequest, options?: RpcOptions): UnaryCall<QueryProbabilityRequest, QueryProbabilityResponse>;
|
||||
/**
|
||||
*
|
||||
* BuildRoute builds a fully specified route based on a list of hop public
|
||||
* keys. It retrieves the relevant channel policies from the graph in order to
|
||||
* calculate the correct fees and time locks.
|
||||
*
|
||||
* @generated from protobuf rpc: BuildRoute(routerrpc.BuildRouteRequest) returns (routerrpc.BuildRouteResponse);
|
||||
*/
|
||||
buildRoute(input: BuildRouteRequest, options?: RpcOptions): UnaryCall<BuildRouteRequest, BuildRouteResponse>;
|
||||
/**
|
||||
*
|
||||
* SubscribeHtlcEvents creates a uni-directional stream from the server to
|
||||
* the client which delivers a stream of htlc events.
|
||||
*
|
||||
* @generated from protobuf rpc: SubscribeHtlcEvents(routerrpc.SubscribeHtlcEventsRequest) returns (stream routerrpc.HtlcEvent);
|
||||
*/
|
||||
subscribeHtlcEvents(input: SubscribeHtlcEventsRequest, options?: RpcOptions): ServerStreamingCall<SubscribeHtlcEventsRequest, HtlcEvent>;
|
||||
/**
|
||||
*
|
||||
* Deprecated, use SendPaymentV2. SendPayment attempts to route a payment
|
||||
* described by the passed PaymentRequest to the final destination. The call
|
||||
* returns a stream of payment status updates.
|
||||
*
|
||||
* @deprecated
|
||||
* @generated from protobuf rpc: SendPayment(routerrpc.SendPaymentRequest) returns (stream routerrpc.PaymentStatus);
|
||||
*/
|
||||
sendPayment(input: SendPaymentRequest, options?: RpcOptions): ServerStreamingCall<SendPaymentRequest, PaymentStatus>;
|
||||
/**
|
||||
*
|
||||
* Deprecated, use TrackPaymentV2. TrackPayment returns an update stream for
|
||||
* the payment identified by the payment hash.
|
||||
*
|
||||
* @deprecated
|
||||
* @generated from protobuf rpc: TrackPayment(routerrpc.TrackPaymentRequest) returns (stream routerrpc.PaymentStatus);
|
||||
*/
|
||||
trackPayment(input: TrackPaymentRequest, options?: RpcOptions): ServerStreamingCall<TrackPaymentRequest, PaymentStatus>;
|
||||
/**
|
||||
* *
|
||||
* HtlcInterceptor dispatches a bi-directional streaming RPC in which
|
||||
* Forwarded HTLC requests are sent to the client and the client responds with
|
||||
* a boolean that tells LND if this htlc should be intercepted.
|
||||
* In case of interception, the htlc can be either settled, cancelled or
|
||||
* resumed later by using the ResolveHoldForward endpoint.
|
||||
*
|
||||
* @generated from protobuf rpc: HtlcInterceptor(stream routerrpc.ForwardHtlcInterceptResponse) returns (stream routerrpc.ForwardHtlcInterceptRequest);
|
||||
*/
|
||||
htlcInterceptor(options?: RpcOptions): DuplexStreamingCall<ForwardHtlcInterceptResponse, ForwardHtlcInterceptRequest>;
|
||||
/**
|
||||
*
|
||||
* UpdateChanStatus attempts to manually set the state of a channel
|
||||
* (enabled, disabled, or auto). A manual "disable" request will cause the
|
||||
* channel to stay disabled until a subsequent manual request of either
|
||||
* "enable" or "auto".
|
||||
*
|
||||
* @generated from protobuf rpc: UpdateChanStatus(routerrpc.UpdateChanStatusRequest) returns (routerrpc.UpdateChanStatusResponse);
|
||||
*/
|
||||
updateChanStatus(input: UpdateChanStatusRequest, options?: RpcOptions): UnaryCall<UpdateChanStatusRequest, UpdateChanStatusResponse>;
|
||||
}
|
||||
/**
|
||||
* Router is a service that offers advanced interaction with the router
|
||||
* subsystem of the daemon.
|
||||
*
|
||||
* @generated from protobuf service routerrpc.Router
|
||||
*/
|
||||
export class RouterClient implements IRouterClient, ServiceInfo {
|
||||
typeName = Router.typeName;
|
||||
methods = Router.methods;
|
||||
options = Router.options;
|
||||
constructor(private readonly _transport: RpcTransport) {
|
||||
}
|
||||
/**
|
||||
*
|
||||
* SendPaymentV2 attempts to route a payment described by the passed
|
||||
* PaymentRequest to the final destination. The call returns a stream of
|
||||
* payment updates.
|
||||
*
|
||||
* @generated from protobuf rpc: SendPaymentV2(routerrpc.SendPaymentRequest) returns (stream lnrpc.Payment);
|
||||
*/
|
||||
sendPaymentV2(input: SendPaymentRequest, options?: RpcOptions): ServerStreamingCall<SendPaymentRequest, Payment> {
|
||||
const method = this.methods[0], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<SendPaymentRequest, Payment>("serverStreaming", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* TrackPaymentV2 returns an update stream for the payment identified by the
|
||||
* payment hash.
|
||||
*
|
||||
* @generated from protobuf rpc: TrackPaymentV2(routerrpc.TrackPaymentRequest) returns (stream lnrpc.Payment);
|
||||
*/
|
||||
trackPaymentV2(input: TrackPaymentRequest, options?: RpcOptions): ServerStreamingCall<TrackPaymentRequest, Payment> {
|
||||
const method = this.methods[1], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<TrackPaymentRequest, Payment>("serverStreaming", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* TrackPayments returns an update stream for every payment that is not in a
|
||||
* terminal state. Note that if payments are in-flight while starting a new
|
||||
* subscription, the start of the payment stream could produce out-of-order
|
||||
* and/or duplicate events. In order to get updates for every in-flight
|
||||
* payment attempt make sure to subscribe to this method before initiating any
|
||||
* payments.
|
||||
*
|
||||
* @generated from protobuf rpc: TrackPayments(routerrpc.TrackPaymentsRequest) returns (stream lnrpc.Payment);
|
||||
*/
|
||||
trackPayments(input: TrackPaymentsRequest, options?: RpcOptions): ServerStreamingCall<TrackPaymentsRequest, Payment> {
|
||||
const method = this.methods[2], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<TrackPaymentsRequest, Payment>("serverStreaming", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* EstimateRouteFee allows callers to obtain a lower bound w.r.t how much it
|
||||
* may cost to send an HTLC to the target end destination.
|
||||
*
|
||||
* @generated from protobuf rpc: EstimateRouteFee(routerrpc.RouteFeeRequest) returns (routerrpc.RouteFeeResponse);
|
||||
*/
|
||||
estimateRouteFee(input: RouteFeeRequest, options?: RpcOptions): UnaryCall<RouteFeeRequest, RouteFeeResponse> {
|
||||
const method = this.methods[3], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<RouteFeeRequest, RouteFeeResponse>("unary", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* Deprecated, use SendToRouteV2. SendToRoute attempts to make a payment via
|
||||
* the specified route. This method differs from SendPayment in that it
|
||||
* allows users to specify a full route manually. This can be used for
|
||||
* things like rebalancing, and atomic swaps. It differs from the newer
|
||||
* SendToRouteV2 in that it doesn't return the full HTLC information.
|
||||
*
|
||||
* @deprecated
|
||||
* @generated from protobuf rpc: SendToRoute(routerrpc.SendToRouteRequest) returns (routerrpc.SendToRouteResponse);
|
||||
*/
|
||||
sendToRoute(input: SendToRouteRequest, options?: RpcOptions): UnaryCall<SendToRouteRequest, SendToRouteResponse> {
|
||||
const method = this.methods[4], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<SendToRouteRequest, SendToRouteResponse>("unary", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* SendToRouteV2 attempts to make a payment via the specified route. This
|
||||
* method differs from SendPayment in that it allows users to specify a full
|
||||
* route manually. This can be used for things like rebalancing, and atomic
|
||||
* swaps.
|
||||
*
|
||||
* @generated from protobuf rpc: SendToRouteV2(routerrpc.SendToRouteRequest) returns (lnrpc.HTLCAttempt);
|
||||
*/
|
||||
sendToRouteV2(input: SendToRouteRequest, options?: RpcOptions): UnaryCall<SendToRouteRequest, HTLCAttempt> {
|
||||
const method = this.methods[5], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<SendToRouteRequest, HTLCAttempt>("unary", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* ResetMissionControl clears all mission control state and starts with a clean
|
||||
* slate.
|
||||
*
|
||||
* @generated from protobuf rpc: ResetMissionControl(routerrpc.ResetMissionControlRequest) returns (routerrpc.ResetMissionControlResponse);
|
||||
*/
|
||||
resetMissionControl(input: ResetMissionControlRequest, options?: RpcOptions): UnaryCall<ResetMissionControlRequest, ResetMissionControlResponse> {
|
||||
const method = this.methods[6], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<ResetMissionControlRequest, ResetMissionControlResponse>("unary", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* QueryMissionControl exposes the internal mission control state to callers.
|
||||
* It is a development feature.
|
||||
*
|
||||
* @generated from protobuf rpc: QueryMissionControl(routerrpc.QueryMissionControlRequest) returns (routerrpc.QueryMissionControlResponse);
|
||||
*/
|
||||
queryMissionControl(input: QueryMissionControlRequest, options?: RpcOptions): UnaryCall<QueryMissionControlRequest, QueryMissionControlResponse> {
|
||||
const method = this.methods[7], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<QueryMissionControlRequest, QueryMissionControlResponse>("unary", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* XImportMissionControl is an experimental API that imports the state provided
|
||||
* to the internal mission control's state, using all results which are more
|
||||
* recent than our existing values. These values will only be imported
|
||||
* in-memory, and will not be persisted across restarts.
|
||||
*
|
||||
* @generated from protobuf rpc: XImportMissionControl(routerrpc.XImportMissionControlRequest) returns (routerrpc.XImportMissionControlResponse);
|
||||
*/
|
||||
xImportMissionControl(input: XImportMissionControlRequest, options?: RpcOptions): UnaryCall<XImportMissionControlRequest, XImportMissionControlResponse> {
|
||||
const method = this.methods[8], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<XImportMissionControlRequest, XImportMissionControlResponse>("unary", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* GetMissionControlConfig returns mission control's current config.
|
||||
*
|
||||
* @generated from protobuf rpc: GetMissionControlConfig(routerrpc.GetMissionControlConfigRequest) returns (routerrpc.GetMissionControlConfigResponse);
|
||||
*/
|
||||
getMissionControlConfig(input: GetMissionControlConfigRequest, options?: RpcOptions): UnaryCall<GetMissionControlConfigRequest, GetMissionControlConfigResponse> {
|
||||
const method = this.methods[9], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<GetMissionControlConfigRequest, GetMissionControlConfigResponse>("unary", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* SetMissionControlConfig will set mission control's config, if the config
|
||||
* provided is valid.
|
||||
*
|
||||
* @generated from protobuf rpc: SetMissionControlConfig(routerrpc.SetMissionControlConfigRequest) returns (routerrpc.SetMissionControlConfigResponse);
|
||||
*/
|
||||
setMissionControlConfig(input: SetMissionControlConfigRequest, options?: RpcOptions): UnaryCall<SetMissionControlConfigRequest, SetMissionControlConfigResponse> {
|
||||
const method = this.methods[10], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<SetMissionControlConfigRequest, SetMissionControlConfigResponse>("unary", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* QueryProbability returns the current success probability estimate for a
|
||||
* given node pair and amount.
|
||||
*
|
||||
* @generated from protobuf rpc: QueryProbability(routerrpc.QueryProbabilityRequest) returns (routerrpc.QueryProbabilityResponse);
|
||||
*/
|
||||
queryProbability(input: QueryProbabilityRequest, options?: RpcOptions): UnaryCall<QueryProbabilityRequest, QueryProbabilityResponse> {
|
||||
const method = this.methods[11], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<QueryProbabilityRequest, QueryProbabilityResponse>("unary", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* BuildRoute builds a fully specified route based on a list of hop public
|
||||
* keys. It retrieves the relevant channel policies from the graph in order to
|
||||
* calculate the correct fees and time locks.
|
||||
*
|
||||
* @generated from protobuf rpc: BuildRoute(routerrpc.BuildRouteRequest) returns (routerrpc.BuildRouteResponse);
|
||||
*/
|
||||
buildRoute(input: BuildRouteRequest, options?: RpcOptions): UnaryCall<BuildRouteRequest, BuildRouteResponse> {
|
||||
const method = this.methods[12], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<BuildRouteRequest, BuildRouteResponse>("unary", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* SubscribeHtlcEvents creates a uni-directional stream from the server to
|
||||
* the client which delivers a stream of htlc events.
|
||||
*
|
||||
* @generated from protobuf rpc: SubscribeHtlcEvents(routerrpc.SubscribeHtlcEventsRequest) returns (stream routerrpc.HtlcEvent);
|
||||
*/
|
||||
subscribeHtlcEvents(input: SubscribeHtlcEventsRequest, options?: RpcOptions): ServerStreamingCall<SubscribeHtlcEventsRequest, HtlcEvent> {
|
||||
const method = this.methods[13], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<SubscribeHtlcEventsRequest, HtlcEvent>("serverStreaming", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* Deprecated, use SendPaymentV2. SendPayment attempts to route a payment
|
||||
* described by the passed PaymentRequest to the final destination. The call
|
||||
* returns a stream of payment status updates.
|
||||
*
|
||||
* @deprecated
|
||||
* @generated from protobuf rpc: SendPayment(routerrpc.SendPaymentRequest) returns (stream routerrpc.PaymentStatus);
|
||||
*/
|
||||
sendPayment(input: SendPaymentRequest, options?: RpcOptions): ServerStreamingCall<SendPaymentRequest, PaymentStatus> {
|
||||
const method = this.methods[14], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<SendPaymentRequest, PaymentStatus>("serverStreaming", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* Deprecated, use TrackPaymentV2. TrackPayment returns an update stream for
|
||||
* the payment identified by the payment hash.
|
||||
*
|
||||
* @deprecated
|
||||
* @generated from protobuf rpc: TrackPayment(routerrpc.TrackPaymentRequest) returns (stream routerrpc.PaymentStatus);
|
||||
*/
|
||||
trackPayment(input: TrackPaymentRequest, options?: RpcOptions): ServerStreamingCall<TrackPaymentRequest, PaymentStatus> {
|
||||
const method = this.methods[15], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<TrackPaymentRequest, PaymentStatus>("serverStreaming", this._transport, method, opt, input);
|
||||
}
|
||||
/**
|
||||
* *
|
||||
* HtlcInterceptor dispatches a bi-directional streaming RPC in which
|
||||
* Forwarded HTLC requests are sent to the client and the client responds with
|
||||
* a boolean that tells LND if this htlc should be intercepted.
|
||||
* In case of interception, the htlc can be either settled, cancelled or
|
||||
* resumed later by using the ResolveHoldForward endpoint.
|
||||
*
|
||||
* @generated from protobuf rpc: HtlcInterceptor(stream routerrpc.ForwardHtlcInterceptResponse) returns (stream routerrpc.ForwardHtlcInterceptRequest);
|
||||
*/
|
||||
htlcInterceptor(options?: RpcOptions): DuplexStreamingCall<ForwardHtlcInterceptResponse, ForwardHtlcInterceptRequest> {
|
||||
const method = this.methods[16], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<ForwardHtlcInterceptResponse, ForwardHtlcInterceptRequest>("duplex", this._transport, method, opt);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* UpdateChanStatus attempts to manually set the state of a channel
|
||||
* (enabled, disabled, or auto). A manual "disable" request will cause the
|
||||
* channel to stay disabled until a subsequent manual request of either
|
||||
* "enable" or "auto".
|
||||
*
|
||||
* @generated from protobuf rpc: UpdateChanStatus(routerrpc.UpdateChanStatusRequest) returns (routerrpc.UpdateChanStatusResponse);
|
||||
*/
|
||||
updateChanStatus(input: UpdateChanStatusRequest, options?: RpcOptions): UnaryCall<UpdateChanStatusRequest, UpdateChanStatusResponse> {
|
||||
const method = this.methods[17], opt = this._transport.mergeOptions(options);
|
||||
return stackIntercept<UpdateChanStatusRequest, UpdateChanStatusResponse>("unary", this._transport, method, opt, input);
|
||||
}
|
||||
}
|
||||
3544
proto/lnd/router.ts
Normal file
3544
proto/lnd/router.ts
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1,6 +1,6 @@
|
|||
syntax = "proto3";
|
||||
|
||||
import "rpc.proto";
|
||||
import "lightning.proto";
|
||||
|
||||
package invoicesrpc;
|
||||
|
||||
|
|
@ -35,10 +35,17 @@ service Invoices {
|
|||
settled, this call will succeed.
|
||||
*/
|
||||
rpc SettleInvoice (SettleInvoiceMsg) returns (SettleInvoiceResp);
|
||||
|
||||
/*
|
||||
LookupInvoiceV2 attempts to look up at invoice. An invoice can be refrenced
|
||||
using either its payment hash, payment address, or set ID.
|
||||
*/
|
||||
rpc LookupInvoiceV2 (LookupInvoiceMsg) returns (lnrpc.Invoice);
|
||||
}
|
||||
|
||||
message CancelInvoiceMsg {
|
||||
// Hash corresponding to the (hold) invoice to cancel.
|
||||
// Hash corresponding to the (hold) invoice to cancel. When using
|
||||
// REST, this field must be encoded as base64.
|
||||
bytes payment_hash = 1;
|
||||
}
|
||||
message CancelInvoiceResp {
|
||||
|
|
@ -98,11 +105,26 @@ message AddHoldInvoiceRequest {
|
|||
|
||||
message AddHoldInvoiceResp {
|
||||
/*
|
||||
A bare-bones invoice for a payment within the Lightning Network. With the
|
||||
A bare-bones invoice for a payment within the Lightning Network. With the
|
||||
details of the invoice, the sender has all the data necessary to send a
|
||||
payment to the recipient.
|
||||
*/
|
||||
string payment_request = 1;
|
||||
|
||||
/*
|
||||
The "add" index of this invoice. Each newly created invoice will increment
|
||||
this index making it monotonically increasing. Callers to the
|
||||
SubscribeInvoices call can use this to instantly get notified of all added
|
||||
invoices with an add_index greater than this one.
|
||||
*/
|
||||
uint64 add_index = 2;
|
||||
|
||||
/*
|
||||
The payment address of the generated invoice. This value should be used
|
||||
in all payments for this invoice as we require it for end to end
|
||||
security.
|
||||
*/
|
||||
bytes payment_addr = 3;
|
||||
}
|
||||
|
||||
message SettleInvoiceMsg {
|
||||
|
|
@ -117,6 +139,37 @@ message SettleInvoiceResp {
|
|||
message SubscribeSingleInvoiceRequest {
|
||||
reserved 1;
|
||||
|
||||
// Hash corresponding to the (hold) invoice to subscribe to.
|
||||
// Hash corresponding to the (hold) invoice to subscribe to. When using
|
||||
// REST, this field must be encoded as base64url.
|
||||
bytes r_hash = 2;
|
||||
}
|
||||
|
||||
enum LookupModifier {
|
||||
// The default look up modifier, no look up behavior is changed.
|
||||
DEFAULT = 0;
|
||||
|
||||
/*
|
||||
Indicates that when a look up is done based on a set_id, then only that set
|
||||
of HTLCs related to that set ID should be returned.
|
||||
*/
|
||||
HTLC_SET_ONLY = 1;
|
||||
|
||||
/*
|
||||
Indicates that when a look up is done using a payment_addr, then no HTLCs
|
||||
related to the payment_addr should be returned. This is useful when one
|
||||
wants to be able to obtain the set of associated setIDs with a given
|
||||
invoice, then look up the sub-invoices "projected" by that set ID.
|
||||
*/
|
||||
HTLC_SET_BLANK = 2;
|
||||
}
|
||||
|
||||
message LookupInvoiceMsg {
|
||||
oneof invoice_ref {
|
||||
// When using REST, this field must be encoded as base64.
|
||||
bytes payment_hash = 1;
|
||||
bytes payment_addr = 2;
|
||||
bytes set_id = 3;
|
||||
}
|
||||
|
||||
LookupModifier lookup_modifier = 4;
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,6 +1,6 @@
|
|||
syntax = "proto3";
|
||||
|
||||
import "rpc.proto";
|
||||
import "lightning.proto";
|
||||
|
||||
package routerrpc;
|
||||
|
||||
|
|
@ -22,6 +22,16 @@ service Router {
|
|||
*/
|
||||
rpc TrackPaymentV2 (TrackPaymentRequest) returns (stream lnrpc.Payment);
|
||||
|
||||
/*
|
||||
TrackPayments returns an update stream for every payment that is not in a
|
||||
terminal state. Note that if payments are in-flight while starting a new
|
||||
subscription, the start of the payment stream could produce out-of-order
|
||||
and/or duplicate events. In order to get updates for every in-flight
|
||||
payment attempt make sure to subscribe to this method before initiating any
|
||||
payments.
|
||||
*/
|
||||
rpc TrackPayments (TrackPaymentsRequest) returns (stream lnrpc.Payment);
|
||||
|
||||
/*
|
||||
EstimateRouteFee allows callers to obtain a lower bound w.r.t how much it
|
||||
may cost to send an HTLC to the target end destination.
|
||||
|
|
@ -284,6 +294,12 @@ message SendPaymentRequest {
|
|||
If set, an AMP-payment will be attempted.
|
||||
*/
|
||||
bool amp = 22;
|
||||
|
||||
/*
|
||||
The time preference for this payment. Set to -1 to optimize for fees
|
||||
only, to 1 to optimize for reliability only or a value inbetween for a mix.
|
||||
*/
|
||||
double time_pref = 23;
|
||||
}
|
||||
|
||||
message TrackPaymentRequest {
|
||||
|
|
@ -297,6 +313,14 @@ message TrackPaymentRequest {
|
|||
bool no_inflight_updates = 2;
|
||||
}
|
||||
|
||||
message TrackPaymentsRequest {
|
||||
/*
|
||||
If set, only the final payment updates are streamed back. Intermediate
|
||||
updates that show which htlcs are still in flight are suppressed.
|
||||
*/
|
||||
bool no_inflight_updates = 1;
|
||||
}
|
||||
|
||||
message RouteFeeRequest {
|
||||
/*
|
||||
The destination once wishes to obtain a routing fee quote to.
|
||||
|
|
@ -330,6 +354,14 @@ message SendToRouteRequest {
|
|||
|
||||
// Route that should be used to attempt to complete the payment.
|
||||
lnrpc.Route route = 2;
|
||||
|
||||
/*
|
||||
Whether the payment should be marked as failed when a temporary error is
|
||||
returned from the given route. Set it to true so the payment won't be
|
||||
failed unless a terminal error is occurred, such as payment timeout, no
|
||||
routes, incorrect payment details, or insufficient funds.
|
||||
*/
|
||||
bool skip_temp_err = 3;
|
||||
}
|
||||
|
||||
message SendToRouteResponse {
|
||||
|
|
@ -360,6 +392,11 @@ message QueryMissionControlResponse {
|
|||
message XImportMissionControlRequest {
|
||||
// Node pair-level mission control state to be imported.
|
||||
repeated PairHistory pairs = 1;
|
||||
|
||||
// Whether to force override MC pair history. Note that even with force
|
||||
// override the failure pair is imported before the success pair and both
|
||||
// still clamp existing failure/success amounts.
|
||||
bool force = 2;
|
||||
}
|
||||
|
||||
message XImportMissionControlResponse {
|
||||
|
|
@ -581,6 +618,8 @@ message HtlcEvent {
|
|||
ForwardFailEvent forward_fail_event = 8;
|
||||
SettleEvent settle_event = 9;
|
||||
LinkFailEvent link_fail_event = 10;
|
||||
SubscribedEvent subscribed_event = 11;
|
||||
FinalHtlcEvent final_htlc_event = 12;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -607,6 +646,16 @@ message ForwardFailEvent {
|
|||
}
|
||||
|
||||
message SettleEvent {
|
||||
// The revealed preimage.
|
||||
bytes preimage = 1;
|
||||
}
|
||||
|
||||
message FinalHtlcEvent {
|
||||
bool settled = 1;
|
||||
bool offchain = 2;
|
||||
}
|
||||
|
||||
message SubscribedEvent {
|
||||
}
|
||||
|
||||
message LinkFailEvent {
|
||||
|
|
@ -676,7 +725,7 @@ enum PaymentState {
|
|||
FAILED_NO_ROUTE = 3;
|
||||
|
||||
/*
|
||||
A non-recoverable error has occured.
|
||||
A non-recoverable error has occurred.
|
||||
*/
|
||||
FAILED_ERROR = 4;
|
||||
|
||||
|
|
@ -753,6 +802,10 @@ message ForwardHtlcInterceptRequest {
|
|||
|
||||
// The onion blob for the next hop
|
||||
bytes onion_blob = 9;
|
||||
|
||||
// The block height at which this htlc will be auto-failed to prevent the
|
||||
// channel from force-closing.
|
||||
int32 auto_fail_height = 10;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -774,6 +827,21 @@ message ForwardHtlcInterceptResponse {
|
|||
|
||||
// The preimage in case the resolve action is Settle.
|
||||
bytes preimage = 3;
|
||||
|
||||
// Encrypted failure message in case the resolve action is Fail.
|
||||
//
|
||||
// If failure_message is specified, the failure_code field must be set
|
||||
// to zero.
|
||||
bytes failure_message = 4;
|
||||
|
||||
// Return the specified failure code in case the resolve action is Fail. The
|
||||
// message data fields are populated automatically.
|
||||
//
|
||||
// If a non-zero failure_code is specified, failure_message must not be set.
|
||||
//
|
||||
// For backwards-compatibility reasons, TEMPORARY_CHANNEL_FAILURE is the
|
||||
// default value for this field.
|
||||
lnrpc.Failure.FailureCode failure_code = 5;
|
||||
}
|
||||
|
||||
enum ResolveHoldForwardAction {
|
||||
|
|
@ -795,4 +863,4 @@ enum ChanStatusAction {
|
|||
}
|
||||
|
||||
message UpdateChanStatusResponse {
|
||||
}
|
||||
}
|
||||
BIN
proto/protoc-gen-pub.exe
Normal file
BIN
proto/protoc-gen-pub.exe
Normal file
Binary file not shown.
122
proto/service/methods.proto
Normal file
122
proto/service/methods.proto
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
syntax = "proto3";
|
||||
|
||||
package methods;
|
||||
|
||||
import "google/protobuf/descriptor.proto";
|
||||
import "structs.proto";
|
||||
|
||||
option go_package = "github.com/shocknet/lightning.pub";
|
||||
option (file_options) = {
|
||||
supported_http_methods:["post", "get"];
|
||||
supported_auths:[
|
||||
{
|
||||
id: "guest"
|
||||
name: "Guest"
|
||||
context:[]
|
||||
},
|
||||
{
|
||||
id: "user"
|
||||
name: "User",
|
||||
context:{
|
||||
key:"user_id",
|
||||
value:"string"
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "admin",
|
||||
name: "Admin",
|
||||
encrypted:true,
|
||||
context:{
|
||||
key:"admin_id",
|
||||
value:"string"
|
||||
}
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
message MethodQueryOptions {
|
||||
repeated string items = 1;
|
||||
}
|
||||
|
||||
extend google.protobuf.MethodOptions { // TODO: move this stuff to dep repo?
|
||||
string auth_type = 50003;
|
||||
string http_method = 50004;
|
||||
string http_route = 50005;
|
||||
MethodQueryOptions query = 50006;
|
||||
|
||||
}
|
||||
|
||||
message ProtoFileOptions {
|
||||
message SupportedAuth {
|
||||
string id = 1;
|
||||
string name = 2;
|
||||
bool encrypted = 3;
|
||||
map<string,string> context = 4;
|
||||
}
|
||||
repeated SupportedAuth supported_auths = 1;
|
||||
repeated string supported_http_methods = 2;
|
||||
}
|
||||
|
||||
extend google.protobuf.FileOptions {
|
||||
ProtoFileOptions file_options = 50004;
|
||||
}
|
||||
|
||||
service LightningPub {
|
||||
rpc Health(structs.Empty) returns (structs.Empty){
|
||||
option (auth_type) = "Guest";
|
||||
option (http_method) = "get";
|
||||
option (http_route) = "/api/health";
|
||||
};
|
||||
rpc EncryptionExchange(structs.EncryptionExchangeRequest) returns (structs.Empty){
|
||||
option (auth_type) = "Guest";
|
||||
option (http_method) = "post";
|
||||
option (http_route) = "/api/encryption/exchange";
|
||||
};
|
||||
rpc LndGetInfo(structs.LndGetInfoRequest) returns (structs.LndGetInfoResponse){
|
||||
option (auth_type) = "Admin";
|
||||
option (http_method) = "post";
|
||||
option (http_route) = "/api/lnd/getinfo";
|
||||
};
|
||||
|
||||
rpc AddUser(structs.AddUserRequest)returns (structs.AddUserResponse){
|
||||
option (auth_type) = "Guest";
|
||||
option (http_method) = "post";
|
||||
option (http_route) = "/api/user/add";
|
||||
}
|
||||
rpc AuthUser(structs.AuthUserRequest)returns (structs.AuthUserResponse){
|
||||
option (auth_type) = "Guest";
|
||||
option (http_method) = "post";
|
||||
option (http_route) = "/api/user/auth";
|
||||
}
|
||||
// USER
|
||||
rpc NewAddress(structs.NewAddressRequest) returns (structs.NewAddressResponse) {
|
||||
option (auth_type) = "User";
|
||||
option (http_method) = "post";
|
||||
option (http_route) = "/api/user/chain/new";
|
||||
}
|
||||
rpc PayAddress(structs.PayAddressRequest) returns (structs.PayAddressResponse){
|
||||
option (auth_type) = "User";
|
||||
option (http_method) = "post";
|
||||
option (http_route) = "/api/user/chain/pay";
|
||||
}
|
||||
rpc NewInvoice(structs.NewInvoiceRequest) returns (structs.NewInvoiceResponse){
|
||||
option (auth_type) = "User";
|
||||
option (http_method) = "post";
|
||||
option (http_route) = "/api/user/invoice/new";
|
||||
}
|
||||
rpc PayInvoice(structs.PayInvoiceRequest) returns (structs.PayInvoiceResponse){
|
||||
option (auth_type) = "User";
|
||||
option (http_method) = "post";
|
||||
option (http_route) = "/api/user/invoice/pay";
|
||||
}
|
||||
rpc OpenChannel(structs.OpenChannelRequest) returns (structs.OpenChannelResponse){
|
||||
option (auth_type) = "User";
|
||||
option (http_method) = "post";
|
||||
option (http_route) = "/api/user/open/channel";
|
||||
}
|
||||
rpc GetOpenChannelLNURL(structs.Empty) returns (structs.GetOpenChannelLNURLResponse){
|
||||
option (auth_type) = "User";
|
||||
option (http_method) = "post";
|
||||
option (http_route) = "/api/user/lnurl_channel";
|
||||
}
|
||||
}
|
||||
93
proto/service/structs.proto
Normal file
93
proto/service/structs.proto
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
syntax = "proto3";
|
||||
|
||||
package structs;
|
||||
|
||||
option go_package = "github.com/shocknet/lightning.pub";
|
||||
|
||||
message Empty {}
|
||||
|
||||
|
||||
message EncryptionExchangeRequest {
|
||||
string public_key = 1;
|
||||
string device_id = 2;
|
||||
}
|
||||
|
||||
message LndGetInfoRequest {
|
||||
int64 node_id = 1;
|
||||
}
|
||||
|
||||
message LndGetInfoResponse {
|
||||
string alias = 1;
|
||||
}
|
||||
enum AddressType {
|
||||
WITNESS_PUBKEY_HASH = 0;
|
||||
NESTED_PUBKEY_HASH = 1;
|
||||
TAPROOT_PUBKEY = 2;
|
||||
}
|
||||
message NewAddressRequest {
|
||||
AddressType address_type = 1;
|
||||
}
|
||||
message NewAddressResponse{
|
||||
string address = 1;
|
||||
}
|
||||
message PayAddressRequest{
|
||||
string address = 1;
|
||||
int64 amout_sats = 2;
|
||||
}
|
||||
|
||||
message PayAddressResponse{
|
||||
string tx_id = 1;
|
||||
}
|
||||
|
||||
message NewInvoiceRequest{
|
||||
int64 amount_sats = 1;
|
||||
}
|
||||
|
||||
message NewInvoiceResponse{
|
||||
string invoice = 1;
|
||||
}
|
||||
|
||||
message PayInvoiceRequest{
|
||||
string invoice = 1;
|
||||
int64 amount = 2;
|
||||
}
|
||||
|
||||
message PayInvoiceResponse{
|
||||
string preimage = 1;
|
||||
}
|
||||
|
||||
message OpenChannelRequest{
|
||||
string destination = 1;
|
||||
int64 funding_amount = 2;
|
||||
int64 push_amount = 3;
|
||||
string close_address = 4;
|
||||
}
|
||||
|
||||
message OpenChannelResponse{
|
||||
string channel_id = 1;
|
||||
}
|
||||
|
||||
message GetOpenChannelLNURLResponse{
|
||||
string lnurl = 1;
|
||||
}
|
||||
|
||||
message AddUserRequest{
|
||||
string callback_url = 1;
|
||||
string name = 2;
|
||||
string secret = 3;
|
||||
}
|
||||
|
||||
message AddUserResponse{
|
||||
string user_id = 1;
|
||||
string auth_token = 2;
|
||||
}
|
||||
|
||||
message AuthUserRequest{
|
||||
string name = 2;
|
||||
string secret = 3;
|
||||
}
|
||||
|
||||
message AuthUserResponse{
|
||||
string user_id = 1;
|
||||
string auth_token = 2;
|
||||
}
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Document</title>
|
||||
<script src="/qrCodeGenerator"></script>
|
||||
</head>
|
||||
<body>
|
||||
<p id="errorContainer"></p>
|
||||
<div>
|
||||
<h3>Tunnel</h3>
|
||||
<p id="tunnelState"></p>
|
||||
</div>
|
||||
<div>
|
||||
<h3>Access Secret</h3>
|
||||
<p id="accessSecretState"></p>
|
||||
</div>
|
||||
<div id="qrcode"></div>
|
||||
<script>
|
||||
fetch(`${window.location.origin}/api/accessInfo`)
|
||||
.then(res => res.json())
|
||||
.then(j => {
|
||||
console.log(j)
|
||||
if(j.field){
|
||||
document.querySelector('#errorContainer').innerHTML ='there was an error, unable to load access information, reason: '+ j.message
|
||||
return
|
||||
}
|
||||
|
||||
const tunnelUrl = handleTunnelInfo(j)
|
||||
const accessCode = handleAccessCode(j)
|
||||
|
||||
const baseUrl = tunnelUrl ? tunnelUrl : window.location.host
|
||||
const finalUrl = accessCode ? `${accessCode}#${baseUrl}` : baseUrl
|
||||
new QRCode(document.getElementById("qrcode"), finalUrl);
|
||||
|
||||
})
|
||||
.catch(e => {
|
||||
console.log(e.message)
|
||||
})
|
||||
|
||||
const handleTunnelInfo = (res) => {
|
||||
|
||||
|
||||
const tunnelState = document.querySelector("#tunnelState")
|
||||
if(res.tunnelDisabled){
|
||||
tunnelState.innerHTML = 'The tunnel service is disabled'
|
||||
return
|
||||
}
|
||||
if(res.relayNotFound) {
|
||||
tunnelState.innerHTML = 'The tunnel service seems broken'
|
||||
return
|
||||
}
|
||||
tunnelState.innerHTML = `Tunnel URL: ${res.relayId}@${res.relayUrl}`
|
||||
return `${res.relayId}@${res.relayUrl}`
|
||||
}
|
||||
|
||||
const handleAccessCode = (res) => {
|
||||
const accessSecretState = document.querySelector("#accessSecretState")
|
||||
if(res.accessSecretDisabled){
|
||||
accessSecretState.innerHTML = 'The access secret is disabled'
|
||||
return
|
||||
}
|
||||
if(res.accessCodeNotFound){
|
||||
accessSecretState.innerHTML = 'The access secret seems broken'
|
||||
return
|
||||
}
|
||||
if(res.accessCodeUsed){
|
||||
accessSecretState.innerHTML = 'The access secret was already used'
|
||||
return
|
||||
}
|
||||
accessSecretState.innerHTML = `Access Secret: ${res.accessCode}`
|
||||
return res.accessCode
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,96 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Document</title>
|
||||
<style>
|
||||
html,
|
||||
body{
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
.main{
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
|
||||
}
|
||||
.content{
|
||||
font-size: 4rem;
|
||||
background: #333333;
|
||||
padding: 1rem;
|
||||
border-radius: 0.5rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
#content-name{
|
||||
color: #FFFFFF;
|
||||
text-shadow: 0 0 10px #FFFFFF;
|
||||
margin:0
|
||||
}
|
||||
#content-message{
|
||||
color: #FFFFFF;
|
||||
text-shadow: 4px 3px 0 #7A7A7A;
|
||||
margin:0
|
||||
|
||||
}
|
||||
#content-amount{
|
||||
color: #FFFFFF;
|
||||
text-shadow: 0 -1px 4px #FFF, 0 -2px 10px #ff0, 0 -10px 20px #ff8000, 0 -18px 40px #F00;
|
||||
margin:0
|
||||
}
|
||||
.hide{
|
||||
display:none
|
||||
}
|
||||
</style>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.1.3/socket.io.msgpack.min.js" crossorigin="anonymous"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="main">
|
||||
<div class="content hide">
|
||||
<p id="content-name">some random name i dont know</p>
|
||||
<p id="content-message">JUST TIPPED YOU!</p>
|
||||
<p id="content-amount">100sats</p>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
const queryString = window.location.search;
|
||||
const urlParams = new URLSearchParams(queryString);
|
||||
const accessId = urlParams.get("accessId")
|
||||
const relayId = urlParams.get("x-shock-hybrid-relay-id-x")
|
||||
|
||||
const socketSetting = {
|
||||
reconnection: true,
|
||||
rejectUnauthorized: false,
|
||||
withCredentials: true,
|
||||
transports: ["websocket"]
|
||||
}
|
||||
var socket = io(`${location.origin}/streams`,socketSetting);
|
||||
socket.emit('hybridRelayId',{id:relayId})
|
||||
socket.on("connect", () => {
|
||||
setTimeout(()=>{socket.emit("accessId",accessId)},500)
|
||||
})
|
||||
let latestTimeout = null
|
||||
socket.on("update",(update)=>{
|
||||
const name = document.querySelector("#content-name")
|
||||
name.innerHTML = update.name
|
||||
const message = document.querySelector("#content-message")
|
||||
message.innerHTML = update.message
|
||||
const amount = document.querySelector("#content-amount")
|
||||
amount.innerHTML = update.amount
|
||||
|
||||
const content = document.querySelector(".content")
|
||||
content.classList.remove("hide")
|
||||
clearTimeout(latestTimeout)
|
||||
latestTimeout = setTimeout(()=>{
|
||||
content.classList.add("hide")
|
||||
},5000)
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
1
public/qrcode.min.js
vendored
1
public/qrcode.min.js
vendored
File diff suppressed because one or more lines are too long
|
|
@ -1,79 +0,0 @@
|
|||
/*
|
||||
* @prettier
|
||||
*/
|
||||
// @ts-nocheck
|
||||
const jwt = require('jsonwebtoken')
|
||||
const uuidv1 = require('uuid/v1')
|
||||
const jsonfile = require('jsonfile')
|
||||
const path = require('path')
|
||||
const logger = require('../../config/log')
|
||||
const Storage = require('node-persist')
|
||||
const FS = require('../../utils/fs')
|
||||
|
||||
const rootFolder = process.resourcesPath || __dirname
|
||||
|
||||
class Auth {
|
||||
readSecrets = async () => {
|
||||
const secrets = await Storage.get('auth/secrets')
|
||||
|
||||
if (secrets) {
|
||||
return secrets
|
||||
}
|
||||
|
||||
const newSecrets = await Storage.set('auth/secrets', {})
|
||||
|
||||
return newSecrets
|
||||
}
|
||||
|
||||
async writeSecrets(key, value) {
|
||||
const allSecrets = await this.readSecrets()
|
||||
const newSecrets = await Storage.set('auth/secrets', {
|
||||
...allSecrets,
|
||||
[key]: value
|
||||
})
|
||||
return newSecrets
|
||||
}
|
||||
|
||||
async generateToken() {
|
||||
const timestamp = Date.now()
|
||||
const secret = uuidv1()
|
||||
logger.info('Generating new secret...')
|
||||
const token = jwt.sign(
|
||||
{
|
||||
data: { timestamp }
|
||||
},
|
||||
secret,
|
||||
{ expiresIn: '500h' }
|
||||
)
|
||||
logger.info('Saving secret...')
|
||||
await this.writeSecrets(timestamp, secret)
|
||||
return token
|
||||
}
|
||||
|
||||
async validateToken(token) {
|
||||
try {
|
||||
const key = jwt.decode(token).data.timestamp
|
||||
const secrets = await this.readSecrets()
|
||||
const secret = secrets[key]
|
||||
if (!secret) {
|
||||
throw { valid: false }
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
jwt.verify(token, secret, (err, decoded) => {
|
||||
if (err) {
|
||||
logger.info('validateToken err', err)
|
||||
reject(err)
|
||||
} else {
|
||||
// logger.info('decoded', decoded)
|
||||
resolve({ valid: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
} catch (err) {
|
||||
logger.error(err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new Auth()
|
||||
|
|
@ -1,491 +0,0 @@
|
|||
/**
|
||||
* @format
|
||||
*/
|
||||
const Common = require('shock-common')
|
||||
const Gun = require('../../../utils/GunSmith')
|
||||
// @ts-ignore
|
||||
require('gun/nts')
|
||||
const logger = require('../../../config/log')
|
||||
// @ts-ignore
|
||||
// Gun.log = () => {}
|
||||
// @ts-ignore
|
||||
require('gun/lib/open')
|
||||
// @ts-ignore
|
||||
require('gun/lib/load')
|
||||
//@ts-ignore
|
||||
const { encryptedEmit, encryptedOn } = require('../../../utils/ECC/socket')
|
||||
const Key = require('../contact-api/key')
|
||||
const Config = require('../config')
|
||||
|
||||
/** @type {import('../contact-api/SimpleGUN').ISEA} */
|
||||
// @ts-ignore
|
||||
const SEAx = require('gun/sea')
|
||||
// Re-enable in the future, when SEA errors inside user.auth/etc actually
|
||||
// propagate up.
|
||||
// SEAx.throw = true
|
||||
|
||||
/** @type {import('../contact-api/SimpleGUN').ISEA} */
|
||||
const mySEA = {}
|
||||
|
||||
// Avoid this: https://github.com/amark/gun/issues/804 and any other issues
|
||||
const $$__SHOCKWALLET__ENCRYPTED__ = '$$_SHOCKWALLET__ENCRYPTED__'
|
||||
const $$__SHOCKWALLET__MSG__ = '$$__SHOCKWALLET__MSG__'
|
||||
const $$__SHOCKWALLET__NUMBER__ = '$$__SHOCKWALLET__NUMBER__'
|
||||
const $$__SHOCKWALLET__BOOLEAN__ = '$$__SHOCKWALLET__BOOLEAN__'
|
||||
|
||||
/// <reference path="../../../utils/GunSmith/Smith.ts" />
|
||||
|
||||
mySEA.encrypt = (msg, secret) => {
|
||||
if (typeof secret !== 'string') {
|
||||
throw new TypeError(
|
||||
`mySEA.encrypt() -> expected secret to be a an string, args: |msg| -- ${JSON.stringify(
|
||||
secret
|
||||
)}`
|
||||
)
|
||||
}
|
||||
|
||||
if (secret.length < 1) {
|
||||
throw new TypeError(
|
||||
`mySEA.encrypt() -> expected secret to be a populated string`
|
||||
)
|
||||
}
|
||||
|
||||
let strToEncode = ''
|
||||
|
||||
if (typeof msg === 'string') {
|
||||
if (msg.length === 0) {
|
||||
throw new TypeError(
|
||||
'mySEA.encrypt() -> expected msg to be a populated string'
|
||||
)
|
||||
}
|
||||
|
||||
strToEncode = $$__SHOCKWALLET__MSG__ + msg
|
||||
} else if (typeof msg === 'boolean') {
|
||||
strToEncode = $$__SHOCKWALLET__BOOLEAN__ + msg
|
||||
} else if (typeof msg === 'number') {
|
||||
strToEncode = $$__SHOCKWALLET__NUMBER__ + msg
|
||||
} else {
|
||||
throw new TypeError('mySea.encrypt() -> Not a valid msg type.')
|
||||
}
|
||||
|
||||
return SEAx.encrypt(strToEncode, secret).then(encMsg => {
|
||||
return $$__SHOCKWALLET__ENCRYPTED__ + encMsg
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} encMsg
|
||||
* @param {string} secret
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
const decryptBase = (encMsg, secret) => {
|
||||
if (typeof encMsg !== 'string') {
|
||||
throw new TypeError(
|
||||
'mySEA.encrypt() -> expected encMsg to be an string instead got: ' +
|
||||
typeof encMsg
|
||||
)
|
||||
}
|
||||
|
||||
if (encMsg.length === 0) {
|
||||
throw new TypeError(
|
||||
'mySEA.encrypt() -> expected encMsg to be a populated string'
|
||||
)
|
||||
}
|
||||
|
||||
if (typeof secret !== 'string') {
|
||||
throw new TypeError('mySea.decrypt() -> expected secret to be an string')
|
||||
}
|
||||
|
||||
if (secret.length === 0) {
|
||||
throw new TypeError(
|
||||
'mySea.decrypt() -> expected secret to be a populated string'
|
||||
)
|
||||
}
|
||||
|
||||
if (encMsg.indexOf($$__SHOCKWALLET__ENCRYPTED__) !== 0) {
|
||||
throw new TypeError(
|
||||
'Trying to pass a non prefixed encrypted string to mySea.decrypt(): ' +
|
||||
encMsg
|
||||
)
|
||||
}
|
||||
|
||||
return SEAx.decrypt(
|
||||
encMsg.slice($$__SHOCKWALLET__ENCRYPTED__.length),
|
||||
secret
|
||||
).then(decodedMsg => {
|
||||
if (typeof decodedMsg !== 'string') {
|
||||
throw new TypeError('Could not decrypt')
|
||||
}
|
||||
|
||||
if (decodedMsg.startsWith($$__SHOCKWALLET__MSG__)) {
|
||||
return decodedMsg.slice($$__SHOCKWALLET__MSG__.length)
|
||||
} else if (decodedMsg.startsWith($$__SHOCKWALLET__BOOLEAN__)) {
|
||||
const dec = decodedMsg.slice($$__SHOCKWALLET__BOOLEAN__.length)
|
||||
if (dec === 'true') {
|
||||
return true
|
||||
} else if (dec === 'false') {
|
||||
return false
|
||||
}
|
||||
throw new Error('Could not decrypt boolean value.')
|
||||
} else if (decodedMsg.startsWith($$__SHOCKWALLET__NUMBER__)) {
|
||||
return Number(decodedMsg.slice($$__SHOCKWALLET__NUMBER__.length))
|
||||
}
|
||||
|
||||
throw new TypeError(
|
||||
`mySea.encrypt() -> Unexpected type of prefix found inside decrypted value, first 20 characters: ${decodedMsg.slice(
|
||||
0,
|
||||
20
|
||||
)}`
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
mySEA.decrypt = (encMsg, secret) => {
|
||||
return decryptBase(encMsg, secret)
|
||||
}
|
||||
|
||||
mySEA.decryptNumber = (encMsg, secret) => {
|
||||
return decryptBase(encMsg, secret)
|
||||
}
|
||||
|
||||
mySEA.decryptBoolean = (encMsg, secret) => {
|
||||
return decryptBase(encMsg, secret)
|
||||
}
|
||||
|
||||
mySEA.secret = async (recipientOrSenderEpub, recipientOrSenderSEA) => {
|
||||
if (typeof recipientOrSenderEpub !== 'string') {
|
||||
throw new TypeError(
|
||||
'epub has to be an string, args:' +
|
||||
`${JSON.stringify(recipientOrSenderEpub)} -- ${JSON.stringify(
|
||||
recipientOrSenderSEA
|
||||
)}`
|
||||
)
|
||||
}
|
||||
if (recipientOrSenderEpub.length === 0) {
|
||||
throw new TypeError(
|
||||
'epub has to be populated string, args: ' +
|
||||
`${JSON.stringify(recipientOrSenderEpub)} -- ${JSON.stringify(
|
||||
recipientOrSenderSEA
|
||||
)}`
|
||||
)
|
||||
}
|
||||
if (typeof recipientOrSenderSEA !== 'object') {
|
||||
throw new TypeError(
|
||||
'sea has to be an object, args: ' +
|
||||
`${JSON.stringify(recipientOrSenderEpub)} -- ${JSON.stringify(
|
||||
recipientOrSenderSEA
|
||||
)}`
|
||||
)
|
||||
}
|
||||
|
||||
if (recipientOrSenderSEA === null) {
|
||||
throw new TypeError(
|
||||
'sea has to be non null, args: ' +
|
||||
`${JSON.stringify(recipientOrSenderEpub)} -- ${JSON.stringify(
|
||||
recipientOrSenderSEA
|
||||
)}`
|
||||
)
|
||||
}
|
||||
|
||||
if (recipientOrSenderEpub === recipientOrSenderSEA.pub) {
|
||||
throw new Error(
|
||||
'Do not use pub for mySecret, args: ' +
|
||||
`${JSON.stringify(recipientOrSenderEpub)} -- ${JSON.stringify(
|
||||
recipientOrSenderSEA
|
||||
)}`
|
||||
)
|
||||
}
|
||||
|
||||
const sec = await SEAx.secret(recipientOrSenderEpub, recipientOrSenderSEA)
|
||||
|
||||
if (typeof sec !== 'string') {
|
||||
throw new TypeError(
|
||||
`Could not generate secret, args: ${JSON.stringify(
|
||||
recipientOrSenderEpub
|
||||
)} -- ${JSON.stringify(recipientOrSenderSEA)}`
|
||||
)
|
||||
}
|
||||
|
||||
if (sec.length === 0) {
|
||||
throw new TypeError(
|
||||
`SEA.secret returned an empty string!, args: ${JSON.stringify(
|
||||
recipientOrSenderEpub
|
||||
)} -- ${JSON.stringify(recipientOrSenderSEA)}`
|
||||
)
|
||||
}
|
||||
|
||||
return sec
|
||||
}
|
||||
|
||||
const { Constants } = require('shock-common')
|
||||
|
||||
const API = require('../contact-api/index')
|
||||
|
||||
/**
|
||||
* @typedef {import('../contact-api/SimpleGUN').GUNNode} GUNNode
|
||||
* @typedef {import('../contact-api/SimpleGUN').UserGUNNode} UserGUNNode
|
||||
* @typedef {import('../contact-api/SimpleGUN').ValidDataValue} ValidDataValue
|
||||
*/
|
||||
|
||||
// TO DO: move to common repo
|
||||
/**
|
||||
* @typedef {object} Emission
|
||||
* @prop {boolean} ok
|
||||
* @prop {any} msg
|
||||
* @prop {Record<string, any>} origBody
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} EncryptedEmissionLegacy
|
||||
* @prop {string} encryptedData
|
||||
* @prop {string} encryptedKey
|
||||
* @prop {string} iv
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} EncryptedEmission
|
||||
* @prop {string} ciphertext
|
||||
* @prop {string} mac
|
||||
* @prop {string} iv
|
||||
* @prop {string} ephemPublicKey
|
||||
*/
|
||||
|
||||
// TO DO: move to common repo
|
||||
/**
|
||||
* @typedef {object} SimpleSocket
|
||||
* @prop {(eventName: string, data?: Emission|EncryptedEmissionLegacy|EncryptedEmission|ValidDataValue) => void} emit
|
||||
* @prop {(eventName: string, handler: (data: any, callback: (err?: any, data?: any) => void) => void) => void} on
|
||||
* @prop {{ auth: { [key: string]: any } }} handshake
|
||||
*/
|
||||
|
||||
/* eslint-disable init-declarations */
|
||||
|
||||
const gun = Gun({
|
||||
axe: false,
|
||||
peers: Config.PEERS
|
||||
})
|
||||
|
||||
const user = gun.user()
|
||||
|
||||
/* eslint-enable init-declarations */
|
||||
|
||||
/** @type {string|null} */
|
||||
let mySec = null
|
||||
|
||||
/** @returns {string} */
|
||||
const getMySecret = () => /** @type {string} */ (mySec)
|
||||
|
||||
let _isAuthenticating = false
|
||||
let _isRegistering = false
|
||||
|
||||
const isAuthenticated = () => typeof user.is === 'object' && user.is !== null
|
||||
const isAuthenticating = () => _isAuthenticating
|
||||
const isRegistering = () => _isRegistering
|
||||
|
||||
/**
|
||||
* @returns {Smith.GunSmithNode}
|
||||
*/
|
||||
const getGun = () => {
|
||||
throw new Error('NO GUNS')
|
||||
}
|
||||
|
||||
const getUser = () => {
|
||||
if (!user.is) {
|
||||
logger.warn('called getUser() without being authenticated')
|
||||
throw new Error(Constants.ErrorCode.NOT_AUTH)
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a promise containing the public key of the newly created user.
|
||||
* @param {string} alias
|
||||
* @param {string} pass
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
const authenticate = async (alias, pass) => {
|
||||
if (!Common.isPopulatedString(alias)) {
|
||||
throw new TypeError(
|
||||
`Expected alias to be a populated string, instead got: ${alias}`
|
||||
)
|
||||
}
|
||||
if (!Common.isPopulatedString(pass)) {
|
||||
throw new TypeError(
|
||||
`Expected pass to be a populated string, instead got: ${pass}`
|
||||
)
|
||||
}
|
||||
|
||||
if (isAuthenticating()) {
|
||||
throw new Error(
|
||||
'Cannot authenticate while another authentication attempt is going on'
|
||||
)
|
||||
}
|
||||
|
||||
_isAuthenticating = true
|
||||
|
||||
const ack = await new Promise(res => {
|
||||
user.auth(alias, pass, _ack => {
|
||||
res(_ack)
|
||||
})
|
||||
})
|
||||
|
||||
_isAuthenticating = false
|
||||
|
||||
if (typeof ack.err === 'string') {
|
||||
throw new Error(ack.err)
|
||||
} else if (typeof ack.sea === 'object') {
|
||||
mySec = await mySEA.secret(user._.sea.epub, user._.sea)
|
||||
// clock skew
|
||||
await new Promise(res => setTimeout(res, 2000))
|
||||
|
||||
await /** @type {Promise<void>} */ (new Promise((res, rej) => {
|
||||
user.get(Key.FOLLOWS).put(
|
||||
{
|
||||
unused: null
|
||||
},
|
||||
ack => {
|
||||
if (ack.err && typeof ack.err !== 'number') {
|
||||
rej(
|
||||
new Error(
|
||||
`Error initializing follows: ${JSON.stringify(
|
||||
ack.err,
|
||||
null,
|
||||
4
|
||||
)}`
|
||||
)
|
||||
)
|
||||
} else {
|
||||
res()
|
||||
}
|
||||
}
|
||||
)
|
||||
}))
|
||||
|
||||
// move this to a subscription; implement off() ? todo
|
||||
API.Jobs.onOrders(user, gun, mySEA)
|
||||
API.Jobs.lastSeenNode(user)
|
||||
API.Events.onSeedBackup(() => {}, user, mySEA)
|
||||
|
||||
return ack.sea.pub
|
||||
} else {
|
||||
logger.info(ack)
|
||||
logger.error(
|
||||
`Unknown error, wrong password? Ack looks like: ${JSON.stringify(ack)}`
|
||||
)
|
||||
throw new Error(`Didn't work, bad password?`)
|
||||
}
|
||||
}
|
||||
|
||||
const logoff = () => {
|
||||
user.leave()
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an user for gun. Returns a promise containing the public key of the
|
||||
* newly created user.
|
||||
* @param {string} alias
|
||||
* @param {string} pass
|
||||
* @throws {Error} If gun is authenticated or is in the process of
|
||||
* authenticating. Use `isAuthenticating()` and `isAuthenticated()` to check for
|
||||
* this first. It can also throw if the alias is already registered on gun.
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
const register = async (alias, pass) => {
|
||||
if (isRegistering()) {
|
||||
throw new Error('Already registering.')
|
||||
}
|
||||
|
||||
if (isAuthenticating()) {
|
||||
throw new Error(
|
||||
'Cannot register while gun is being authenticated (reminder: there should only be one user created for each node).'
|
||||
)
|
||||
}
|
||||
|
||||
if (isAuthenticated()) {
|
||||
throw new Error(
|
||||
'Cannot register if gun is already authenticated (reminder: there should only be one user created for each node).'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Peers provided to gun.
|
||||
*/
|
||||
const peers = Object.values(gun._.opt.peers)
|
||||
|
||||
const theresPeers = peers.length > 0
|
||||
const atLeastOneIsConnected = peers.some(
|
||||
p => p.wire && p.wire.readyState === 1
|
||||
)
|
||||
|
||||
if (theresPeers && !atLeastOneIsConnected) {
|
||||
throw new Error(
|
||||
'Not connected to any peers for checking of duplicate aliases'
|
||||
)
|
||||
}
|
||||
|
||||
if (theresPeers && atLeastOneIsConnected) {
|
||||
await new Promise(res => setTimeout(res, 300))
|
||||
|
||||
const userData = await new Promise(res => {
|
||||
gun.get(`~@${alias}`).once(ud => res(ud), {
|
||||
// https://github.com/amark/gun/pull/971#issue-438630761
|
||||
wait: 1500
|
||||
})
|
||||
})
|
||||
|
||||
if (userData) {
|
||||
throw new Error(
|
||||
'The given alias has been used before, use a unique alias instead. (Caught at 2nd try)'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
_isRegistering = true
|
||||
|
||||
/** @type {import('../contact-api/SimpleGUN').CreateAck} */
|
||||
const ack = await new Promise(res =>
|
||||
user.create(alias, pass, ack => res(ack))
|
||||
)
|
||||
|
||||
// An empty ack object seems to be caused by a duplicate alias sign up
|
||||
if ('{}' === JSON.stringify(ack)) {
|
||||
throw new Error(
|
||||
'The given alias has been used before, use an unique alias instead. (Empty ack)'
|
||||
)
|
||||
}
|
||||
|
||||
_isRegistering = false
|
||||
|
||||
if (typeof ack.err === 'string') {
|
||||
throw new Error(ack.err)
|
||||
} else if (typeof ack.pub === 'string' || typeof user._.sea === 'object') {
|
||||
// OK
|
||||
} else {
|
||||
throw new Error('unknown error, ack: ' + JSON.stringify(ack))
|
||||
}
|
||||
|
||||
// restart instances so write to user graph work, there's an issue with gun
|
||||
// (at least on node) where after initial user creation, writes to user graph
|
||||
// don't work
|
||||
// instantiateGun()
|
||||
|
||||
logoff()
|
||||
|
||||
return authenticate(alias, pass)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
authenticate,
|
||||
isAuthenticated,
|
||||
isAuthenticating,
|
||||
isRegistering,
|
||||
gun,
|
||||
user,
|
||||
register,
|
||||
getGun,
|
||||
getUser,
|
||||
mySEA,
|
||||
getMySecret,
|
||||
logoff,
|
||||
$$__SHOCKWALLET__ENCRYPTED__
|
||||
}
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
/**
|
||||
* @format
|
||||
*/
|
||||
/* eslint-disable no-process-env */
|
||||
|
||||
const dotenv = require('dotenv')
|
||||
const defaults = require('../../config/defaults')(false)
|
||||
|
||||
dotenv.config()
|
||||
|
||||
// @ts-ignore Let it crash if undefined
|
||||
exports.DATA_FILE_NAME = process.env.DATA_FILE_NAME || defaults.dataFileName
|
||||
|
||||
/**
|
||||
* @type {string[]}
|
||||
*/
|
||||
exports.PEERS = process.env.PEERS
|
||||
? JSON.parse(process.env.PEERS)
|
||||
: defaults.peers
|
||||
|
||||
exports.MS_TO_TOKEN_EXPIRATION = Number(
|
||||
process.env.MS_TO_TOKEN_EXPIRATION || defaults.tokenExpirationMS
|
||||
)
|
||||
|
||||
exports.SHOW_LOG = process.env.SHOW_GUN_DB_LOG === 'true'
|
||||
|
|
@ -1,149 +0,0 @@
|
|||
/**
|
||||
* @prettier
|
||||
*/
|
||||
export type Primitive = boolean | string | number
|
||||
|
||||
export interface Data {
|
||||
[K: string]: ValidDataValue
|
||||
}
|
||||
|
||||
export type ValidDataValue = Primitive | null | Data
|
||||
|
||||
export interface Ack {
|
||||
err: string | undefined
|
||||
}
|
||||
|
||||
type ListenerObjSoul = {
|
||||
'#': string
|
||||
}
|
||||
|
||||
export type ListenerObj = Record<string, ListenerObjSoul | Primitive | null> & {
|
||||
_: ListenerObjSoul
|
||||
}
|
||||
|
||||
export type ListenerData = Primitive | null | ListenerObj | undefined
|
||||
|
||||
interface OpenListenerDataObj {
|
||||
[k: string]: OpenListenerData
|
||||
}
|
||||
|
||||
export type Listener = (data: ListenerData, key: string) => void
|
||||
export type Callback = (ack: Ack) => void
|
||||
|
||||
export interface Peer {
|
||||
url: string
|
||||
id: string
|
||||
wire?: {
|
||||
readyState: number
|
||||
}
|
||||
}
|
||||
|
||||
export interface Soul {
|
||||
get: string
|
||||
put: Primitive | null | object | undefined
|
||||
opt: {
|
||||
peers: Record<string, Peer>
|
||||
}
|
||||
}
|
||||
|
||||
export type OpenListenerData = Primitive | null | OpenListenerDataObj
|
||||
export type OpenListener = (data: OpenListenerData, key: string) => void
|
||||
|
||||
export type LoadListenerData = OpenListenerData
|
||||
export type LoadListener = (data: LoadListenerData, key: string) => void
|
||||
|
||||
export interface GUNNodeBase {
|
||||
_: Soul
|
||||
|
||||
map(): GUNNode
|
||||
|
||||
on(this: GUNNode, cb: Listener): void
|
||||
once(this: GUNNode, cb?: Listener, opts?: { wait: number }): GUNNode
|
||||
|
||||
open(this: GUNNode, cb?: OpenListener): GUNNode
|
||||
load(this: GUNNode, cb?: OpenListener): GUNNode
|
||||
|
||||
load(this: GUNNode, cb?: LoadListener): GUNNode
|
||||
|
||||
off(): void
|
||||
user(): UserGUNNode
|
||||
user(epub: string): GUNNode
|
||||
|
||||
then(): Promise<ListenerData>
|
||||
then<T>(cb: (v: ListenerData) => T): Promise<ListenerData>
|
||||
}
|
||||
|
||||
export interface GUNNode extends GUNNodeBase {
|
||||
get(key: string): GUNNode
|
||||
put(data: ValidDataValue | GUNNode, cb?: Callback): GUNNode
|
||||
set(data: ValidDataValue | GUNNode, cb?: Callback): GUNNode
|
||||
}
|
||||
|
||||
export interface CreateAck {
|
||||
pub: string | undefined
|
||||
err: string | undefined
|
||||
}
|
||||
|
||||
export type CreateCB = (ack: CreateAck) => void
|
||||
|
||||
export interface AuthAck {
|
||||
err: string | undefined
|
||||
sea:
|
||||
| {
|
||||
pub: string
|
||||
}
|
||||
| undefined
|
||||
}
|
||||
|
||||
export type AuthCB = (ack: AuthAck) => void
|
||||
|
||||
export interface UserPair {
|
||||
epriv: string
|
||||
epub: string
|
||||
priv: string
|
||||
pub: string
|
||||
}
|
||||
|
||||
export interface UserSoul extends Soul {
|
||||
sea: UserPair
|
||||
}
|
||||
|
||||
export interface UserGUNNode extends GUNNode {
|
||||
_: UserSoul
|
||||
auth(user: string, pass: string, cb: AuthCB): void
|
||||
is?: {
|
||||
alias: string
|
||||
pub: string
|
||||
}
|
||||
create(user: string, pass: string, cb: CreateCB): void
|
||||
leave(): void
|
||||
}
|
||||
|
||||
export interface ISEA {
|
||||
encrypt(
|
||||
message: string | number | boolean,
|
||||
senderSecret: string
|
||||
): Promise<string>
|
||||
decrypt(encryptedMessage: string, recipientSecret: string): Promise<string>
|
||||
decryptNumber(
|
||||
encryptedMessage: string,
|
||||
recipientSecret: string
|
||||
): Promise<number>
|
||||
decryptBoolean(
|
||||
encryptedMessage: string,
|
||||
recipientSecret: string
|
||||
): Promise<boolean>
|
||||
secret(
|
||||
recipientOrSenderEpub: string,
|
||||
recipientOrSenderUserPair: UserPair
|
||||
): Promise<string>
|
||||
}
|
||||
|
||||
export interface MySEA {
|
||||
encrypt(message: string, senderSecret: string): Promise<string>
|
||||
decrypt(encryptedMessage: string, recipientSecret: string): Promise<string>
|
||||
secret(
|
||||
recipientOrSenderEpub: string,
|
||||
recipientOrSenderUserPair: UserPair
|
||||
): Promise<string>
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,45 +0,0 @@
|
|||
/**
|
||||
* @prettier
|
||||
*/
|
||||
const debounce = require('lodash/debounce')
|
||||
|
||||
const {
|
||||
Constants: { ErrorCode }
|
||||
} = require('shock-common')
|
||||
|
||||
const Key = require('../key')
|
||||
/// <reference path="../../../utils/GunSmith/Smith.ts" />
|
||||
|
||||
const DEBOUNCE_WAIT_TIME = 500
|
||||
|
||||
/** @type {string|null} */
|
||||
let currentSeedBackup = null
|
||||
|
||||
/**
|
||||
* @param {(seedBackup: string|null) => void} cb
|
||||
* @param {Smith.UserSmithNode} user
|
||||
* @param {import('../SimpleGUN').ISEA} SEA
|
||||
* @throws {Error} If user hasn't been auth.
|
||||
* @returns {void}
|
||||
*/
|
||||
const onSeedBackup = (cb, user, SEA) => {
|
||||
if (!user.is) {
|
||||
throw new Error(ErrorCode.NOT_AUTH)
|
||||
}
|
||||
|
||||
const mySecret = require('../../Mediator').getMySecret()
|
||||
|
||||
const callb = debounce(cb, DEBOUNCE_WAIT_TIME)
|
||||
callb(currentSeedBackup)
|
||||
|
||||
user.get(Key.SEED_BACKUP).on(async seedBackup => {
|
||||
if (typeof seedBackup === 'string') {
|
||||
currentSeedBackup = await SEA.decrypt(seedBackup, mySecret)
|
||||
callb(currentSeedBackup)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
onSeedBackup
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
/**
|
||||
* @format
|
||||
*/
|
||||
|
||||
const Key = require('../key')
|
||||
|
||||
/**
|
||||
* @param {string} pub
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
exports.currentOrderAddress = async pub => {
|
||||
const currAddr = await require('../../Mediator')
|
||||
.getGun()
|
||||
.user(pub)
|
||||
.get(Key.CURRENT_ORDER_ADDRESS)
|
||||
.specialThen()
|
||||
|
||||
if (typeof currAddr !== 'string') {
|
||||
throw new TypeError('Expected user.currentOrderAddress to be an string')
|
||||
}
|
||||
|
||||
return currAddr
|
||||
}
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
/**
|
||||
* @prettier
|
||||
*/
|
||||
const Actions = require('./actions')
|
||||
const Events = require('./events')
|
||||
const Jobs = require('./jobs')
|
||||
const Key = require('./key')
|
||||
|
||||
module.exports = { Actions, Events, Jobs, Key }
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
/**
|
||||
* @format
|
||||
* Jobs are subscriptions to events that perform actions (write to GUN) on
|
||||
* response to certain ways events can happen. These tasks need to be fired up
|
||||
* at app launch otherwise certain features won't work as intended. Tasks should
|
||||
* ideally be idempotent, that is, if they were to be fired up after a certain
|
||||
* amount of time after app launch, everything should work as intended. For this
|
||||
* to work, special care has to be put into how these respond to events. These
|
||||
* tasks accept factories that are homonymous to the events on this same module.
|
||||
*/
|
||||
|
||||
const onOrders = require('./onOrders')
|
||||
const lastSeenNode = require('./lastSeenNode')
|
||||
|
||||
module.exports = {
|
||||
onOrders,
|
||||
lastSeenNode
|
||||
}
|
||||
|
|
@ -1,61 +0,0 @@
|
|||
/**
|
||||
* @format
|
||||
*/
|
||||
|
||||
const logger = require('../../../../config/log')
|
||||
|
||||
const {
|
||||
Constants: {
|
||||
ErrorCode,
|
||||
Misc: { LAST_SEEN_NODE_INTERVAL }
|
||||
}
|
||||
} = require('shock-common')
|
||||
const Key = require('../key')
|
||||
/// <reference path="../../../utils/GunSmith/Smith.ts" />
|
||||
|
||||
/**
|
||||
* @typedef {Smith.GunSmithNode} GUNNode
|
||||
* @typedef {GunT.ListenerData} ListenerData
|
||||
* @typedef {import('../SimpleGUN').ISEA} ISEA
|
||||
* @typedef {Smith.UserSmithNode} UserGUNNode
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {UserGUNNode} user
|
||||
* @throws {Error} NOT_AUTH
|
||||
* @returns {void}
|
||||
*/
|
||||
const lastSeenNode = user => {
|
||||
if (!user.is) {
|
||||
logger.warn('lastSeenNode() -> tried to sub without authing')
|
||||
throw new Error(ErrorCode.NOT_AUTH)
|
||||
}
|
||||
|
||||
let gotLatestProfileAck = true
|
||||
|
||||
setInterval(() => {
|
||||
if (!user.is) {
|
||||
return
|
||||
}
|
||||
if (!gotLatestProfileAck) {
|
||||
logger.error(`lastSeenNode profile job: didnt get latest ack`)
|
||||
return
|
||||
}
|
||||
gotLatestProfileAck = false
|
||||
user
|
||||
.get(Key.PROFILE)
|
||||
.get(Key.LAST_SEEN_NODE)
|
||||
.put(Date.now(), ack => {
|
||||
if (
|
||||
ack.err &&
|
||||
typeof ack.err !== 'number' &&
|
||||
typeof ack.err !== 'object'
|
||||
) {
|
||||
logger.error(`Error inside lastSeenNode profile job: ${ack.err}`)
|
||||
}
|
||||
gotLatestProfileAck = true
|
||||
})
|
||||
}, LAST_SEEN_NODE_INTERVAL)
|
||||
}
|
||||
|
||||
module.exports = lastSeenNode
|
||||
|
|
@ -1,627 +0,0 @@
|
|||
/**
|
||||
* @format
|
||||
*/
|
||||
// @ts-check
|
||||
const logger = require('../../../../config/log')
|
||||
const isFinite = require('lodash/isFinite')
|
||||
const isNumber = require('lodash/isNumber')
|
||||
const isNaN = require('lodash/isNaN')
|
||||
const Common = require('shock-common')
|
||||
const {
|
||||
Constants: { ErrorCode },
|
||||
Schema
|
||||
} = Common
|
||||
const SchemaManager = require('../../../schema')
|
||||
const LightningServices = require('../../../../utils/lightningServices')
|
||||
const Key = require('../key')
|
||||
const Utils = require('../utils')
|
||||
const { selfContentToken, enrollContentTokens } = require('../../../seed')
|
||||
/// <reference path="../../../utils/GunSmith/Smith.ts" />
|
||||
const TipForwarder = require('../../../tipsCallback')
|
||||
|
||||
const getUser = () => require('../../Mediator').getUser()
|
||||
|
||||
/**
|
||||
* @type {Set<string>}
|
||||
*/
|
||||
const ordersProcessed = new Set()
|
||||
|
||||
/**
|
||||
* @typedef {Smith.GunSmithNode} GUNNode
|
||||
* @typedef {GunT.ListenerData} ListenerData
|
||||
* @typedef {import('../SimpleGUN').ISEA} ISEA
|
||||
* @typedef {Smith.UserSmithNode} UserGUNNode
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} InvoiceRequest
|
||||
* @prop {number} expiry
|
||||
* @prop {string} memo
|
||||
* @prop {number} value
|
||||
* @prop {boolean} private
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} InvoiceResponse
|
||||
* @prop {string} payment_request
|
||||
* @prop {Buffer} r_hash
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} TipPaymentStatus
|
||||
* @prop {string} hash
|
||||
* @prop {import('shock-common').Schema.InvoiceState} state
|
||||
* @prop {string} targetType
|
||||
* @prop {(string)=} postID
|
||||
*/
|
||||
|
||||
let currentOrderAddr = ''
|
||||
|
||||
/**
|
||||
* @param {InvoiceRequest} invoiceReq
|
||||
* @returns {Promise<InvoiceResponse>}
|
||||
*/
|
||||
const _addInvoice = invoiceReq =>
|
||||
new Promise((resolve, rej) => {
|
||||
const {
|
||||
services: { lightning }
|
||||
} = LightningServices
|
||||
|
||||
lightning.addInvoice(invoiceReq, (
|
||||
/** @type {any} */ error,
|
||||
/** @type {InvoiceResponse} */ response
|
||||
) => {
|
||||
if (error) {
|
||||
rej(error)
|
||||
} else {
|
||||
resolve(response)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* @param {string} addr
|
||||
* @param {ISEA} SEA
|
||||
* @returns {(order: ListenerData, orderID: string) => void}
|
||||
*/
|
||||
const listenerForAddr = (addr, SEA) => async (order, orderID) => {
|
||||
try {
|
||||
if (addr !== currentOrderAddr) {
|
||||
logger.info(
|
||||
orderID,
|
||||
`order address: ${addr} invalidated (current address: ${currentOrderAddr})`
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Was recycled
|
||||
if (order === null) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!Schema.isOrder(order)) {
|
||||
logger.info(
|
||||
orderID,
|
||||
`Expected an order instead got: ${JSON.stringify(order)}`
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Gun might callback several times for the same order, avoid dupe
|
||||
// processing.
|
||||
if (ordersProcessed.has(orderID)) {
|
||||
return
|
||||
}
|
||||
|
||||
//const listenerStartTime = performance.now()
|
||||
|
||||
ordersProcessed.add(orderID)
|
||||
|
||||
if (Date.now() - order.timestamp > 66000) {
|
||||
logger.info('Not processing old order', orderID)
|
||||
return
|
||||
}
|
||||
|
||||
logger.info('processing order ', orderID)
|
||||
|
||||
const alreadyAnswered = await getUser()
|
||||
.get(Key.ORDER_TO_RESPONSE)
|
||||
.get(orderID)
|
||||
.then()
|
||||
|
||||
if (alreadyAnswered) {
|
||||
logger.info(orderID, 'alreadyAnswered')
|
||||
return
|
||||
}
|
||||
|
||||
logger.info(orderID, ' was not answered, will now answer')
|
||||
|
||||
const senderEpub = await Utils.pubToEpub(order.from)
|
||||
const secret = await SEA.secret(senderEpub, getUser()._.sea)
|
||||
|
||||
const [decryptedAmount, memo] = await Promise.all([
|
||||
SEA.decrypt(order.amount, secret),
|
||||
SEA.decrypt(order.memo, secret)
|
||||
])
|
||||
|
||||
const amount = Number(decryptedAmount)
|
||||
|
||||
if (!isNumber(amount)) {
|
||||
throw new TypeError(
|
||||
`${orderID} Could not parse decrypted amount as a number, not a number?, decryptedAmount: ${decryptedAmount}`
|
||||
)
|
||||
}
|
||||
|
||||
if (isNaN(amount)) {
|
||||
throw new TypeError(
|
||||
`${orderID} Could not parse decrypted amount as a number, got NaN, decryptedAmount: ${decryptedAmount}`
|
||||
)
|
||||
}
|
||||
|
||||
if (!isFinite(amount)) {
|
||||
throw new TypeError(
|
||||
`${orderID} Amount was correctly decrypted, but got a non finite number, decryptedAmount: ${decryptedAmount}`
|
||||
)
|
||||
}
|
||||
const mySecret = require('../../Mediator').getMySecret()
|
||||
/**
|
||||
* @type {string|null}
|
||||
*/
|
||||
let serviceOrderType = null //if the order refers to a service, we take the info from the service before sending the invoice
|
||||
/**
|
||||
* @type {{ seedUrl: string, seedToken: string }|null}
|
||||
*/
|
||||
let serviceOrderContentSeedInfo = null //in case the service is of type 'torrentSeed' this is {seedUrl,seedToken}, can be omitted, in that case, it will be taken from env
|
||||
if (order.targetType === 'service') {
|
||||
logger.info(orderID, 'General Service')
|
||||
const { ackInfo: serviceID } = order
|
||||
logger.info(orderID, 'ACK INFO')
|
||||
logger.info(orderID, serviceID)
|
||||
if (!Common.isPopulatedString(serviceID)) {
|
||||
throw new TypeError(`${orderID} no serviceID provided to orderAck`)
|
||||
}
|
||||
const selectedService = await getUser()
|
||||
.get(Key.OFFERED_SERVICES)
|
||||
.get(serviceID)
|
||||
.then()
|
||||
|
||||
logger.info(orderID, selectedService)
|
||||
if (!Common.isObj(selectedService)) {
|
||||
throw new TypeError(
|
||||
`${orderID} invalid serviceID provided to orderAck or service is not an object`
|
||||
)
|
||||
}
|
||||
|
||||
const {
|
||||
serviceType,
|
||||
servicePrice,
|
||||
serviceSeedUrl: encSeedUrl, //=
|
||||
serviceSeedToken: encSeedToken //=
|
||||
} = /** @type {Record<string, any>} */ (selectedService)
|
||||
if (Number(amount) !== Number(servicePrice)) {
|
||||
throw new TypeError(
|
||||
`${orderID} service price mismatch ${amount} : ${servicePrice}`
|
||||
)
|
||||
}
|
||||
if (serviceType === 'torrentSeed') {
|
||||
if (encSeedUrl && encSeedToken) {
|
||||
const seedUrl = await SEA.decrypt(encSeedUrl, mySecret)
|
||||
const seedToken = await SEA.decrypt(encSeedToken, mySecret)
|
||||
serviceOrderContentSeedInfo = { seedUrl, seedToken }
|
||||
}
|
||||
}
|
||||
|
||||
serviceOrderType = serviceType
|
||||
}
|
||||
|
||||
const invoiceReq = {
|
||||
expiry: 36000,
|
||||
memo,
|
||||
value: amount,
|
||||
private: true
|
||||
}
|
||||
|
||||
const invoice = await _addInvoice(invoiceReq)
|
||||
|
||||
logger.info(
|
||||
`${orderID} onOrders() -> Successfully created the invoice, will now encrypt it`
|
||||
)
|
||||
|
||||
const encInvoice = await SEA.encrypt(invoice.payment_request, secret)
|
||||
|
||||
logger.info(
|
||||
`${orderID} onOrders() -> Will now place the encrypted invoice in order to response usergraph: ${addr}`
|
||||
)
|
||||
|
||||
const ackNode = Utils.gunID()
|
||||
|
||||
/** @type {import('shock-common').Schema.OrderResponse} */
|
||||
const orderResponse = {
|
||||
response: encInvoice,
|
||||
type: 'invoice',
|
||||
ackNode
|
||||
}
|
||||
|
||||
await /** @type {Promise<void>} */ (new Promise((res, rej) => {
|
||||
getUser()
|
||||
.get(Key.ORDER_TO_RESPONSE)
|
||||
.get(orderID)
|
||||
// @ts-expect-error
|
||||
.put(orderResponse, ack => {
|
||||
if (
|
||||
ack.err &&
|
||||
typeof ack.err !== 'number' &&
|
||||
typeof ack.err !== 'object'
|
||||
) {
|
||||
rej(
|
||||
new Error(
|
||||
`${orderID} Error saving encrypted invoice to order to response usergraph: ${ack}`
|
||||
)
|
||||
)
|
||||
} else {
|
||||
res()
|
||||
}
|
||||
})
|
||||
}))
|
||||
|
||||
//logger.info(`[PERF] Added invoice to GunDB in ${invoicePutEndTime}ms`)
|
||||
/**
|
||||
*
|
||||
* @param {Common.Schema.InvoiceWhenListed & {r_hash:Buffer,payment_addr:Buffer}} paidInvoice
|
||||
*/
|
||||
const invoicePaidCb = async paidInvoice => {
|
||||
logger.info(orderID, 'INVOICE PAID')
|
||||
// Recycle
|
||||
require('../../Mediator')
|
||||
.getGun()
|
||||
.get('orderNodes')
|
||||
.get(addr)
|
||||
.get(orderID)
|
||||
.put(null)
|
||||
|
||||
let breakError = null
|
||||
let orderMetadata //eslint-disable-line init-declarations
|
||||
const hashString = paidInvoice.r_hash.toString('hex')
|
||||
const {
|
||||
amt_paid_sat: amt,
|
||||
add_index: addIndex,
|
||||
payment_addr
|
||||
} = paidInvoice
|
||||
const paymentAddr = payment_addr.toString('hex')
|
||||
const orderType = serviceOrderType || order.targetType
|
||||
const { ackInfo } = order //a string representing what has been requested
|
||||
switch (orderType) {
|
||||
case 'tip': {
|
||||
const postID = ackInfo
|
||||
if (!Common.isPopulatedString(postID)) {
|
||||
breakError = orderID + ' invalid ackInfo provided for postID'
|
||||
break //create the coordinate, but stop because of the invalid id
|
||||
}
|
||||
getUser()
|
||||
.get(Key.POSTS_NEW)
|
||||
.get(postID)
|
||||
.get('tipsSet')
|
||||
.set(amt) // each item in the set is a tip
|
||||
|
||||
TipForwarder.notifySocketIfAny(
|
||||
postID,
|
||||
order.from,
|
||||
paidInvoice.memo || 'TIPPED YOU',
|
||||
amt + ' sats'
|
||||
)
|
||||
const ackData = { tippedPost: postID }
|
||||
const toSend = JSON.stringify(ackData)
|
||||
const encrypted = await SEA.encrypt(toSend, secret)
|
||||
const ordResponse = {
|
||||
type: 'orderAck',
|
||||
response: encrypted
|
||||
}
|
||||
await new Promise((res, rej) => {
|
||||
getUser()
|
||||
.get(Key.ORDER_TO_RESPONSE)
|
||||
.get(ackNode)
|
||||
.put(ordResponse, ack => {
|
||||
if (
|
||||
ack.err &&
|
||||
typeof ack.err !== 'number' &&
|
||||
typeof ack.err !== 'object'
|
||||
) {
|
||||
rej(
|
||||
new Error(
|
||||
`${orderID} Error saving encrypted orderAck to order to response usergraph: ${ack}`
|
||||
)
|
||||
)
|
||||
} else {
|
||||
res(null)
|
||||
}
|
||||
})
|
||||
})
|
||||
orderMetadata = JSON.stringify(ackData)
|
||||
break
|
||||
}
|
||||
case 'spontaneousPayment': {
|
||||
//no action required
|
||||
break
|
||||
}
|
||||
case 'contentReveal': {
|
||||
logger.info(orderID, 'CONTENT REVEAL')
|
||||
//assuming digital product that only requires to be unlocked
|
||||
const postID = ackInfo
|
||||
logger.info(orderID, 'ACK INFO')
|
||||
logger.info(ackInfo)
|
||||
if (!Common.isPopulatedString(postID)) {
|
||||
breakError = 'invalid ackInfo provided for postID'
|
||||
break //create the coordinate, but stop because of the invalid id
|
||||
}
|
||||
logger.info(orderID, 'IS STRING')
|
||||
const selectedPost = /** @type {Record<string, any>} */ (await getUser()
|
||||
.get(Key.POSTS_NEW)
|
||||
.get(postID)
|
||||
.then())
|
||||
const selectedPostContent = /** @type {Record<string, any>} */ (await getUser()
|
||||
.get(Key.POSTS_NEW)
|
||||
.get(postID)
|
||||
.get(Key.CONTENT_ITEMS)
|
||||
.then())
|
||||
|
||||
logger.info(orderID, 'LOAD ok')
|
||||
logger.info(selectedPost)
|
||||
if (
|
||||
!selectedPost ||
|
||||
!selectedPost.status ||
|
||||
selectedPost.status !== 'publish'
|
||||
) {
|
||||
breakError = 'ackInfo provided does not correspond to a valid post'
|
||||
break //create the coordinate, but stop because of the invalid post
|
||||
}
|
||||
logger.info(orderID, 'IS POST')
|
||||
/**
|
||||
* @type {Record<string,string>} <contentID,decryptedRef>
|
||||
*/
|
||||
const contentsToSend = {}
|
||||
logger.info(orderID, 'SECRET OK')
|
||||
let privateFound = false
|
||||
await Common.Utils.asyncForEach(
|
||||
Object.entries(selectedPostContent),
|
||||
async ([contentID, item]) => {
|
||||
if (
|
||||
item.type !== 'image/embedded' &&
|
||||
item.type !== 'video/embedded'
|
||||
) {
|
||||
return //only visual content can be private
|
||||
}
|
||||
if (!item.isPrivate) {
|
||||
return
|
||||
}
|
||||
privateFound = true
|
||||
const decrypted = await SEA.decrypt(item.magnetURI, mySecret)
|
||||
contentsToSend[contentID] = decrypted
|
||||
}
|
||||
)
|
||||
if (!privateFound) {
|
||||
breakError =
|
||||
'post provided from ackInfo does not contain private content'
|
||||
break //no private content in this post
|
||||
}
|
||||
const ackData = { unlockedContents: contentsToSend, ackInfo }
|
||||
const toSend = JSON.stringify(ackData)
|
||||
const encrypted = await SEA.encrypt(toSend, secret)
|
||||
const ordResponse = {
|
||||
type: 'orderAck',
|
||||
response: encrypted
|
||||
}
|
||||
logger.info(orderID, 'RES READY')
|
||||
|
||||
await new Promise((res, rej) => {
|
||||
getUser()
|
||||
.get(Key.ORDER_TO_RESPONSE)
|
||||
.get(ackNode)
|
||||
.put(ordResponse, ack => {
|
||||
if (
|
||||
ack.err &&
|
||||
typeof ack.err !== 'number' &&
|
||||
typeof ack.err !== 'object'
|
||||
) {
|
||||
rej(
|
||||
new Error(
|
||||
`Error saving encrypted orderAck to order to response usergraph: ${ack}`
|
||||
)
|
||||
)
|
||||
} else {
|
||||
res(null)
|
||||
}
|
||||
})
|
||||
})
|
||||
logger.info(orderID, 'RES SENT CONTENT')
|
||||
orderMetadata = JSON.stringify(ackData)
|
||||
break
|
||||
}
|
||||
case 'torrentSeed': {
|
||||
logger.info(orderID, 'TORRENT')
|
||||
const numberOfTokens = Number(ackInfo) || 1
|
||||
const seedInfo = selfContentToken()
|
||||
if (!seedInfo && !serviceOrderContentSeedInfo) {
|
||||
breakError = 'torrentSeed service not available'
|
||||
break //service not available
|
||||
}
|
||||
const seedInfoReady = serviceOrderContentSeedInfo || seedInfo
|
||||
if (!seedInfoReady) {
|
||||
breakError = 'torrentSeed service not available'
|
||||
break //service not available
|
||||
}
|
||||
const { seedUrl } = seedInfoReady
|
||||
const tokens = await enrollContentTokens(
|
||||
numberOfTokens,
|
||||
seedInfoReady
|
||||
)
|
||||
logger.info(orderID, 'RES SEED OK')
|
||||
const ackData = { seedUrl, tokens, ackInfo }
|
||||
const toSend = JSON.stringify(ackData)
|
||||
const encrypted = await SEA.encrypt(toSend, secret)
|
||||
const serviceResponse = {
|
||||
type: 'orderAck',
|
||||
response: encrypted
|
||||
}
|
||||
logger.info(orderID, 'RES SEED SENT')
|
||||
await new Promise((res, rej) => {
|
||||
getUser()
|
||||
.get(Key.ORDER_TO_RESPONSE)
|
||||
.get(ackNode)
|
||||
.put(serviceResponse, ack => {
|
||||
if (
|
||||
ack.err &&
|
||||
typeof ack.err !== 'number' &&
|
||||
typeof ack.err !== 'object'
|
||||
) {
|
||||
rej(
|
||||
new Error(
|
||||
`Error saving encrypted orderAck to order to response usergraph: ${ack}`
|
||||
)
|
||||
)
|
||||
} else {
|
||||
res(null)
|
||||
}
|
||||
})
|
||||
})
|
||||
logger.info(orderID, 'RES SENT SEED')
|
||||
orderMetadata = JSON.stringify(ackData)
|
||||
break
|
||||
}
|
||||
case 'other': //not implemented yet but save them as a coordinate anyways
|
||||
break
|
||||
default:
|
||||
breakError = 'invalid service type provided'
|
||||
return //exit because not implemented
|
||||
}
|
||||
const metadata = breakError ? JSON.stringify(breakError) : orderMetadata
|
||||
const myGunPub = getUser()._.sea.pub
|
||||
SchemaManager.AddOrder({
|
||||
type: orderType,
|
||||
coordinateHash: hashString,
|
||||
coordinateIndex: parseInt(addIndex, 10),
|
||||
inbound: true,
|
||||
amount: parseInt(amt, 10),
|
||||
|
||||
toLndPub: paymentAddr,
|
||||
fromGunPub: order.from,
|
||||
toGunPub: myGunPub,
|
||||
invoiceMemo: memo,
|
||||
|
||||
metadata
|
||||
})
|
||||
if (breakError) {
|
||||
throw new Error(breakError)
|
||||
}
|
||||
}
|
||||
logger.info(orderID, 'Waiting for invoice to be paid for order ' + orderID)
|
||||
new Promise(res => SchemaManager.addListenInvoice(invoice.r_hash, res))
|
||||
.then(invoicePaidCb)
|
||||
.catch(err => {
|
||||
logger.error(
|
||||
orderID,
|
||||
`error inside onOrders, orderAddr: ${addr}, orderID: ${orderID}, order: ${JSON.stringify(
|
||||
order
|
||||
)}`
|
||||
)
|
||||
logger.error(orderID, err)
|
||||
logger.info(orderID, err)
|
||||
|
||||
/** @type {import('shock-common').Schema.OrderResponse} */
|
||||
const orderResponse = {
|
||||
response: err.message,
|
||||
type: 'err'
|
||||
}
|
||||
|
||||
getUser()
|
||||
.get(Key.ORDER_TO_RESPONSE)
|
||||
.get(orderID)
|
||||
// @ts-expect-error
|
||||
.put(orderResponse, ack => {
|
||||
if (
|
||||
ack.err &&
|
||||
typeof ack.err !== 'number' &&
|
||||
typeof ack.err !== 'object'
|
||||
) {
|
||||
logger.error(
|
||||
orderID,
|
||||
`Error saving encrypted invoice to order to response usergraph: ${ack}`
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
} catch (/** @type {any} */ err) {
|
||||
logger.error(
|
||||
orderID,
|
||||
`error inside onOrders, orderAddr: ${addr}, orderID: ${orderID}, order: ${JSON.stringify(
|
||||
order
|
||||
)}`
|
||||
)
|
||||
logger.error(orderID, err)
|
||||
logger.info(orderID, err)
|
||||
|
||||
/** @type {import('shock-common').Schema.OrderResponse} */
|
||||
const orderResponse = {
|
||||
response: err.message,
|
||||
type: 'err'
|
||||
}
|
||||
|
||||
getUser()
|
||||
.get(Key.ORDER_TO_RESPONSE)
|
||||
.get(orderID)
|
||||
// @ts-expect-error
|
||||
.put(orderResponse, ack => {
|
||||
if (
|
||||
ack.err &&
|
||||
typeof ack.err !== 'number' &&
|
||||
typeof ack.err !== 'object'
|
||||
) {
|
||||
logger.error(
|
||||
orderID,
|
||||
`Error saving encrypted invoice to order to response usergraph: ${ack}`
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {UserGUNNode} user
|
||||
* @param {GUNNode} gun
|
||||
* @param {ISEA} SEA
|
||||
* @throws {Error} NOT_AUTH
|
||||
* @returns {void}
|
||||
*/
|
||||
const onOrders = (user, gun, SEA) => {
|
||||
if (!user.is) {
|
||||
logger.warn('onOrders() -> tried to sub without authing')
|
||||
throw new Error(ErrorCode.NOT_AUTH)
|
||||
}
|
||||
|
||||
user.get(Key.CURRENT_ORDER_ADDRESS).on(addr => {
|
||||
try {
|
||||
if (typeof addr !== 'string') {
|
||||
logger.error('Expected current order address to be an string')
|
||||
return
|
||||
}
|
||||
|
||||
if (currentOrderAddr === addr) {
|
||||
// Already subscribed
|
||||
return
|
||||
}
|
||||
|
||||
currentOrderAddr = addr
|
||||
logger.info(`listening to address: ${addr}`)
|
||||
|
||||
gun
|
||||
.get(Key.ORDER_NODES)
|
||||
.get(addr)
|
||||
.map()
|
||||
.on(listenerForAddr(currentOrderAddr, SEA))
|
||||
} catch (e) {
|
||||
logger.error(`Could not subscribe to order node: ${addr}, error:`)
|
||||
logger.error(e)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
module.exports = onOrders
|
||||
|
|
@ -1,75 +0,0 @@
|
|||
/**
|
||||
* @format
|
||||
*/
|
||||
exports.HANDSHAKE_NODES = 'handshakeNodes'
|
||||
|
||||
exports.CURRENT_HANDSHAKE_ADDRESS = 'currentHandshakeAddress'
|
||||
|
||||
exports.MESSAGES = 'messages'
|
||||
exports.OUTGOINGS = 'outgoings'
|
||||
|
||||
exports.RECIPIENT_TO_OUTGOING = 'recipientToOutgoing'
|
||||
exports.USER_TO_INCOMING = 'userToIncoming'
|
||||
|
||||
exports.STORED_REQS = 'storedReqs'
|
||||
|
||||
exports.BLACKLIST = 'blacklist'
|
||||
|
||||
exports.PROFILE = 'Profile'
|
||||
exports.AVATAR = 'avatar'
|
||||
exports.DISPLAY_NAME = 'displayName'
|
||||
|
||||
/**
|
||||
* Maps user to the last request sent to them.
|
||||
*/
|
||||
exports.USER_TO_LAST_REQUEST_SENT = 'USER_TO_LAST_REQUEST_SENT'
|
||||
|
||||
exports.CURRENT_ORDER_ADDRESS = 'currentOrderAddress'
|
||||
|
||||
exports.ORDER_NODES = 'orderNodes'
|
||||
|
||||
/**
|
||||
* Another user that placed an order can look for a response in here.
|
||||
*/
|
||||
exports.ORDER_TO_RESPONSE = 'orderToResponse'
|
||||
|
||||
exports.BIO = 'bio'
|
||||
|
||||
exports.SEED_BACKUP = 'seedBackup'
|
||||
|
||||
exports.CHANNELS_BACKUP = 'channelsBackup'
|
||||
|
||||
exports.LAST_SEEN_APP = 'lastSeenApp'
|
||||
|
||||
exports.LAST_SEEN_NODE = 'lastSeenNode'
|
||||
|
||||
exports.WALL = 'wall'
|
||||
|
||||
exports.NUM_OF_PAGES = 'numOfPages'
|
||||
|
||||
exports.PAGES = 'pages'
|
||||
|
||||
exports.COUNT = 'count'
|
||||
|
||||
exports.CONTENT_ITEMS = 'contentItems'
|
||||
exports.FOLLOWS = 'follows'
|
||||
|
||||
exports.POSTS = 'posts'
|
||||
|
||||
// Tips counter for posts
|
||||
exports.TOTAL_TIPS = 'totalTips'
|
||||
|
||||
exports.PROFILE_BINARY = 'profileBinary'
|
||||
|
||||
exports.POSTS_NEW = 'posts'
|
||||
|
||||
// For Coordinates
|
||||
exports.COORDINATES = 'coordinates'
|
||||
|
||||
exports.COORDINATE_INDEX = 'coordinateIndex'
|
||||
|
||||
exports.TMP_CHAIN_COORDINATE = 'tmpChainCoordinate'
|
||||
|
||||
exports.DATE_COORDINATE_INDEX = 'dateCoordinateIndex'
|
||||
|
||||
exports.OFFERED_SERVICES = 'offeredServices'
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
/** @format */
|
||||
|
||||
module.exports = {
|
||||
getPubToLastSeenApp: require('./pubToLastSeenApp').getPubToLastSeenApp,
|
||||
onPubToLastSeenApp: require('./pubToLastSeenApp').on
|
||||
}
|
||||
|
|
@ -1,50 +0,0 @@
|
|||
const Key = require('../key')
|
||||
/**
|
||||
* @typedef {Record<string, number|undefined|null>} Timestamps
|
||||
* @typedef {(timestamps: Timestamps) => void} Listener
|
||||
*/
|
||||
|
||||
/** @type {Timestamps} */
|
||||
const pubToLastSeenApp = {}
|
||||
|
||||
const getPubToLastSeenApp = () => pubToLastSeenApp
|
||||
|
||||
/** @type {Set<Listener>} */
|
||||
const listeners = new Set()
|
||||
|
||||
const notifyListeners = () => {
|
||||
listeners.forEach(l => l(pubToLastSeenApp))
|
||||
}
|
||||
|
||||
/** @type {Set<string>} */
|
||||
const pubsWithListeners = new Set()
|
||||
|
||||
/**
|
||||
* @param {Listener} cb
|
||||
* @param {string=} pub
|
||||
*/
|
||||
const on = (cb, pub) => {
|
||||
listeners.add(cb)
|
||||
cb(pubToLastSeenApp)
|
||||
if (pub && pubsWithListeners.add(pub)) {
|
||||
pubToLastSeenApp[pub] = null
|
||||
notifyListeners()
|
||||
require('../../Mediator')
|
||||
.getGun()
|
||||
.user(pub)
|
||||
.get(Key.LAST_SEEN_APP)
|
||||
.on(timestamp => {
|
||||
pubToLastSeenApp[pub] =
|
||||
typeof timestamp === 'number' ? timestamp : undefined
|
||||
notifyListeners()
|
||||
})
|
||||
}
|
||||
return () => {
|
||||
listeners.delete(cb)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getPubToLastSeenApp,
|
||||
on
|
||||
}
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
/** @format */
|
||||
import { GUNNode, GUNNodeBase, ValidDataValue } from '../SimpleGUN'
|
||||
|
||||
export interface PGUNNode extends GUNNodeBase {
|
||||
get(key: string): PGUNNode
|
||||
put(data: ValidDataValue | GUNNode): Promise<void>
|
||||
set(data: ValidDataValue | GUNNode): Promise<void>
|
||||
}
|
||||
|
|
@ -1,243 +0,0 @@
|
|||
/**
|
||||
* @format
|
||||
*/
|
||||
/* eslint-disable init-declarations */
|
||||
const logger = require('../../../../config/log')
|
||||
const { Constants, Utils: CommonUtils } = require('shock-common')
|
||||
|
||||
const Key = require('../key')
|
||||
/// <reference path="../../../../utils/GunSmith/Smith.ts" />
|
||||
|
||||
/**
|
||||
* @typedef {Smith.GunSmithNode} GUNNode
|
||||
* @typedef {import('../SimpleGUN').ISEA} ISEA
|
||||
* @typedef {Smith.UserSmithNode} UserGUNNode
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {number} ms
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
const delay = ms => new Promise(res => setTimeout(res, ms))
|
||||
|
||||
/**
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
const mySecret = () => Promise.resolve(require('../../Mediator').getMySecret())
|
||||
|
||||
/**
|
||||
* Just a pointer.
|
||||
*/
|
||||
const TIMEOUT_PTR = {}
|
||||
|
||||
/**
|
||||
* @param {number} ms Milliseconds
|
||||
* @returns {<T>(promise: Promise<T>) => Promise<T>}
|
||||
*/
|
||||
const timeout = ms => async promise => {
|
||||
/** @type {NodeJS.Timeout} */
|
||||
// @ts-ignore
|
||||
let timeoutID
|
||||
|
||||
const result = await Promise.race([
|
||||
promise.then(v => {
|
||||
clearTimeout(timeoutID)
|
||||
return v
|
||||
}),
|
||||
|
||||
CommonUtils.makePromise(res => {
|
||||
timeoutID = setTimeout(() => {
|
||||
clearTimeout(timeoutID)
|
||||
res(TIMEOUT_PTR)
|
||||
}, ms)
|
||||
})
|
||||
])
|
||||
|
||||
if (result === TIMEOUT_PTR) {
|
||||
throw new Error(Constants.TIMEOUT_ERR)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Time outs at 10 seconds.
|
||||
*/
|
||||
const timeout10 = timeout(10)
|
||||
|
||||
/**
|
||||
* Time outs at 5 seconds.
|
||||
*/
|
||||
const timeout5 = timeout(5)
|
||||
|
||||
/**
|
||||
* Time outs at 2 seconds.
|
||||
*/
|
||||
const timeout2 = timeout(2)
|
||||
|
||||
/**
|
||||
* @template T
|
||||
* @param {(gun: GUNNode, user: UserGUNNode) => Promise<T>} promGen The function
|
||||
* receives the most recent gun and user instances.
|
||||
* @param {((resolvedValue: unknown) => boolean)=} shouldRetry
|
||||
* @returns {Promise<T>}
|
||||
*/
|
||||
const tryAndWait = async (promGen, shouldRetry = () => false) => {
|
||||
/* eslint-disable init-declarations */
|
||||
|
||||
// If hang stop at 10, wait 3, retry, if hang stop at 5, reinstate, warm for
|
||||
// 5, retry, stop at 10, err
|
||||
|
||||
/** @type {T} */
|
||||
let resolvedValue
|
||||
|
||||
try {
|
||||
resolvedValue = await timeout2(
|
||||
promGen(
|
||||
require('../../Mediator/index').getGun(),
|
||||
require('../../Mediator/index').getUser()
|
||||
)
|
||||
)
|
||||
|
||||
if (!shouldRetry(resolvedValue)) {
|
||||
return resolvedValue
|
||||
}
|
||||
} catch (e) {
|
||||
if (e.message !== Constants.ErrorCode.TIMEOUT_ERR) {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
await delay(200)
|
||||
|
||||
try {
|
||||
resolvedValue = await timeout5(
|
||||
promGen(
|
||||
require('../../Mediator/index').getGun(),
|
||||
require('../../Mediator/index').getUser()
|
||||
)
|
||||
)
|
||||
|
||||
if (!shouldRetry(resolvedValue)) {
|
||||
return resolvedValue
|
||||
}
|
||||
} catch (e) {
|
||||
if (e.message !== Constants.ErrorCode.TIMEOUT_ERR) {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
await delay(3000)
|
||||
|
||||
try {
|
||||
resolvedValue = await timeout5(
|
||||
promGen(
|
||||
require('../../Mediator/index').getGun(),
|
||||
require('../../Mediator/index').getUser()
|
||||
)
|
||||
)
|
||||
|
||||
if (!shouldRetry(resolvedValue)) {
|
||||
return resolvedValue
|
||||
}
|
||||
} catch (e) {
|
||||
if (e.message !== Constants.ErrorCode.TIMEOUT_ERR) {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
return timeout10(
|
||||
promGen(
|
||||
require('../../Mediator/index').getGun(),
|
||||
require('../../Mediator/index').getUser()
|
||||
)
|
||||
)
|
||||
|
||||
/* eslint-enable init-declarations */
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} pub
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
const pubToEpub = async pub => {
|
||||
try {
|
||||
const epub = await require('../../Mediator/index')
|
||||
.getGun()
|
||||
.user(pub)
|
||||
.get('epub')
|
||||
.specialThen()
|
||||
|
||||
return /** @type {string} */ (epub)
|
||||
} catch (err) {
|
||||
logger.error(
|
||||
`Error inside pubToEpub for pub ${pub.slice(0, 8)}...${pub.slice(-8)}:`
|
||||
)
|
||||
logger.error(err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('../SimpleGUN').ListenerData} listenerData
|
||||
* @returns {listenerData is import('../SimpleGUN').ListenerObj}
|
||||
*/
|
||||
const dataHasSoul = listenerData =>
|
||||
typeof listenerData === 'object' && listenerData !== null
|
||||
|
||||
/**
|
||||
* @param {string} pub
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
const isNodeOnline = async pub => {
|
||||
const SET_LAST_SEEN_APP_INTERVAL = 15000
|
||||
|
||||
/**
|
||||
* @param {any} lastSeen
|
||||
* @returns {boolean}
|
||||
*/
|
||||
const isAppOnline = lastSeen =>
|
||||
typeof lastSeen === 'number' &&
|
||||
Date.now() - lastSeen < SET_LAST_SEEN_APP_INTERVAL * 2
|
||||
|
||||
const userNode = require('../../Mediator')
|
||||
.getGun()
|
||||
.user(pub)
|
||||
|
||||
const isOnlineApp = isAppOnline(await userNode.get(Key.LAST_SEEN_APP).then())
|
||||
const lastSeenNode = await userNode.get(Key.LAST_SEEN_NODE).then()
|
||||
|
||||
return (
|
||||
isOnlineApp ||
|
||||
(typeof lastSeenNode === 'number' &&
|
||||
Date.now() - lastSeenNode < Constants.Misc.LAST_SEEN_NODE_INTERVAL * 2)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {string}
|
||||
*/
|
||||
const gunID = () => {
|
||||
// Copied from gun internals
|
||||
let s = ''
|
||||
let l = 24 // you are not going to make a 0 length random number, so no need to check type
|
||||
const c = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXZabcdefghijklmnopqrstuvwxyz'
|
||||
while (l > 0) {
|
||||
s += c.charAt(Math.floor(Math.random() * c.length))
|
||||
l--
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
dataHasSoul,
|
||||
delay,
|
||||
pubToEpub,
|
||||
tryAndWait,
|
||||
mySecret,
|
||||
promisifyGunNode: require('./promisifygun'),
|
||||
timeout5,
|
||||
timeout2,
|
||||
isNodeOnline,
|
||||
gunID
|
||||
}
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
/**
|
||||
* @format
|
||||
*/
|
||||
const expect = require('expect')
|
||||
|
||||
const { gunID } = require('./index')
|
||||
|
||||
describe('gunID()', () => {
|
||||
it('generates 24-chars-long unique IDs', () => {
|
||||
const id = gunID()
|
||||
expect(id).toBeTruthy()
|
||||
expect(id.length).toBe(24)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,55 +0,0 @@
|
|||
/**
|
||||
* @format
|
||||
* @typedef {import("../SimpleGUN").ValidDataValue} ValidDataValue
|
||||
* @typedef {import('../SimpleGUN').GUNNode} GUNNode
|
||||
* @typedef {import('./PGUNNode').PGUNNode} PGUNNode
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {GUNNode} node
|
||||
* @returns {PGUNNode}
|
||||
*/
|
||||
const promisify = node => {
|
||||
const oldPut = node.put.bind(node)
|
||||
const oldSet = node.set.bind(node)
|
||||
const oldGet = node.get.bind(node)
|
||||
|
||||
const _pnode = /** @type {unknown} */ (node)
|
||||
const pnode = /** @type {PGUNNode} */ (_pnode)
|
||||
|
||||
pnode.put = data =>
|
||||
new Promise((res, rej) => {
|
||||
oldPut(data, ack => {
|
||||
if (
|
||||
ack.err &&
|
||||
typeof ack.err !== 'number' &&
|
||||
typeof ack.err !== 'object'
|
||||
) {
|
||||
rej(new Error(ack.err))
|
||||
} else {
|
||||
res()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
pnode.set = data =>
|
||||
new Promise((res, rej) => {
|
||||
oldSet(data, ack => {
|
||||
if (
|
||||
ack.err &&
|
||||
typeof ack.err !== 'number' &&
|
||||
typeof ack.err !== 'object'
|
||||
) {
|
||||
rej(new Error(ack.err))
|
||||
} else {
|
||||
res()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
pnode.get = key => promisify(oldGet(key))
|
||||
|
||||
return pnode
|
||||
}
|
||||
|
||||
module.exports = promisify
|
||||
|
|
@ -1,315 +0,0 @@
|
|||
/**
|
||||
* @format
|
||||
*/
|
||||
/* eslint-disable no-use-before-define */
|
||||
// @ts-check
|
||||
const { makePromise, Constants, Schema } = require('shock-common')
|
||||
const mapValues = require('lodash/mapValues')
|
||||
const Bluebird = require('bluebird')
|
||||
|
||||
const { pubToEpub } = require('../contact-api/utils')
|
||||
const {
|
||||
getGun,
|
||||
getUser,
|
||||
mySEA: SEA,
|
||||
getMySecret,
|
||||
$$__SHOCKWALLET__ENCRYPTED__
|
||||
} = require('../Mediator')
|
||||
const logger = require('../../../config/log')
|
||||
const Utils = require('../contact-api/utils')
|
||||
/**
|
||||
* @typedef {import('../contact-api/SimpleGUN').ValidDataValue} ValidDataValue
|
||||
* @typedef {import('./types').ValidRPCDataValue} ValidRPCDataValue
|
||||
* @typedef {import('./types').RPCData} RPCData
|
||||
*/
|
||||
|
||||
const PATH_SEPARATOR = '>'
|
||||
|
||||
/**
|
||||
* @param {ValidDataValue} value
|
||||
* @param {string} publicKey
|
||||
* @param {string=} epubForDecryption
|
||||
* @returns {Promise<ValidDataValue>}
|
||||
*/
|
||||
const deepDecryptIfNeeded = async (value, publicKey, epubForDecryption) => {
|
||||
if (Schema.isObj(value)) {
|
||||
return Bluebird.props(
|
||||
mapValues(value, o =>
|
||||
deepDecryptIfNeeded(o, publicKey, epubForDecryption)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
if (
|
||||
typeof value === 'string' &&
|
||||
value.indexOf($$__SHOCKWALLET__ENCRYPTED__) === 0
|
||||
) {
|
||||
const user = getUser()
|
||||
if (!user.is) {
|
||||
throw new Error(Constants.ErrorCode.NOT_AUTH)
|
||||
}
|
||||
|
||||
let sec = ''
|
||||
if (user.is.pub === publicKey || 'me' === publicKey) {
|
||||
sec = getMySecret()
|
||||
} else {
|
||||
let epub = epubForDecryption
|
||||
|
||||
if (!epub) {
|
||||
epub = await pubToEpub(publicKey)
|
||||
}
|
||||
|
||||
sec = await SEA.secret(epub, user._.sea)
|
||||
}
|
||||
|
||||
const decrypted = SEA.decrypt(value, sec)
|
||||
|
||||
return decrypted
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ValidRPCDataValue} value
|
||||
* @returns {Promise<ValidRPCDataValue>}
|
||||
*/
|
||||
// eslint-disable-next-line func-style
|
||||
async function deepEncryptIfNeeded(value) {
|
||||
const u = getUser()
|
||||
|
||||
if (!u.is) {
|
||||
throw new Error(Constants.ErrorCode.NOT_AUTH)
|
||||
}
|
||||
|
||||
if (!Schema.isObj(value)) {
|
||||
return value
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return Promise.all(value.map(v => deepEncryptIfNeeded(v)))
|
||||
}
|
||||
|
||||
const pk = /** @type {string|undefined} */ (value.$$__ENCRYPT__FOR)
|
||||
const epub = /** @type {string|undefined} */ (value.$$__EPUB__FOR)
|
||||
|
||||
if (!pk) {
|
||||
return Bluebird.props(mapValues(value, deepEncryptIfNeeded))
|
||||
}
|
||||
|
||||
const actualValue = /** @type {string} */ (value.value)
|
||||
|
||||
let encryptedValue = ''
|
||||
|
||||
if (pk === u.is.pub || pk === 'me') {
|
||||
encryptedValue = await SEA.encrypt(actualValue, getMySecret())
|
||||
} else {
|
||||
const sec = await SEA.secret(
|
||||
await (() => {
|
||||
if (epub) {
|
||||
return epub
|
||||
}
|
||||
return pubToEpub(pk)
|
||||
})(),
|
||||
u._.sea
|
||||
)
|
||||
|
||||
encryptedValue = await SEA.encrypt(actualValue, sec)
|
||||
}
|
||||
|
||||
return encryptedValue
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} rawPath
|
||||
* @param {ValidRPCDataValue} value
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
const put = async (rawPath, value) => {
|
||||
const [root, ...path] = rawPath.split(PATH_SEPARATOR)
|
||||
|
||||
const node = (() => {
|
||||
// eslint-disable-next-line init-declarations
|
||||
let _node
|
||||
|
||||
if (root === '$gun') {
|
||||
_node = getGun()
|
||||
} else if (root === '$user') {
|
||||
const u = getUser()
|
||||
|
||||
if (!u.is) {
|
||||
throw new Error(Constants.ErrorCode.NOT_AUTH)
|
||||
}
|
||||
|
||||
_node = u
|
||||
} else {
|
||||
throw new TypeError(
|
||||
`Unknown kind of root, expected $gun or $user but got: ${root}`
|
||||
)
|
||||
}
|
||||
|
||||
for (const bit of path) {
|
||||
_node = _node.get(bit)
|
||||
}
|
||||
|
||||
return _node
|
||||
})()
|
||||
|
||||
const theValue = await deepEncryptIfNeeded(value)
|
||||
|
||||
if (Array.isArray(theValue)) {
|
||||
await Promise.all(theValue.map(v => set(rawPath, v)))
|
||||
|
||||
// Do not remove this return, an array is also an object
|
||||
// eslint-disable-next-line no-useless-return
|
||||
return
|
||||
} else if (Schema.isObj(theValue)) {
|
||||
const currValue = await node.then()
|
||||
|
||||
if (Schema.isObj(currValue)) {
|
||||
const writes = mapValues(theValue, (v, k) =>
|
||||
put(rawPath + PATH_SEPARATOR + k, v)
|
||||
)
|
||||
|
||||
await Bluebird.props(writes)
|
||||
} else {
|
||||
// if the value at path foo is null or another primitive, then
|
||||
// foo.get('bar').put(baz) will NOT work, the write needs to happen like so:
|
||||
// foo.put({ bar: baz }). Doing foo.put({}) also works but it won't replace
|
||||
// the primitive value with an empty object but with the last object
|
||||
// representation of that node. Doing foo.put({ anything: whatever }) will
|
||||
// merge that new object with the previous representation too. Both of which
|
||||
// can result in inconsistent states so please thread carefully. What I
|
||||
// chose to do here was put without waiting for ack, and if the actual
|
||||
// user-generated puts fail, roll back to the previous local state in order
|
||||
// to accomplish some kind of atomicity. This bug will mostly affect maps
|
||||
// instead of sets as deleted keys in a set should not be reused.
|
||||
// Maps should conform to an schema to avoid inconsistent data.
|
||||
try {
|
||||
node.put({}) // changes from current primitive value to last known object value
|
||||
|
||||
const writes = mapValues(theValue, (v, k) =>
|
||||
put(rawPath + PATH_SEPARATOR + k, v)
|
||||
)
|
||||
|
||||
await Bluebird.props(writes)
|
||||
} catch (e) {
|
||||
if (typeof currValue !== 'undefined') {
|
||||
// if write was somehow unsuccessful, revert to last known primitive value
|
||||
node.put(currValue)
|
||||
}
|
||||
|
||||
throw e
|
||||
}
|
||||
}
|
||||
} /* is primitive */ else {
|
||||
await makePromise((res, rej) => {
|
||||
node.put(/** @type {ValidDataValue} */ (theValue), ack => {
|
||||
if (
|
||||
ack.err &&
|
||||
typeof ack.err !== 'number' &&
|
||||
typeof ack.err !== 'object'
|
||||
) {
|
||||
if (typeof ack.err === 'string') {
|
||||
rej(new Error(ack.err))
|
||||
} else {
|
||||
logger.info(`NON STANDARD GUN ERROR:`)
|
||||
logger.info(ack)
|
||||
rej(new Error(JSON.stringify(ack.err, null, 4)))
|
||||
}
|
||||
} else {
|
||||
res()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} rawPath
|
||||
* @param {ValidRPCDataValue} value
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
// eslint-disable-next-line func-style
|
||||
async function set(rawPath, value) {
|
||||
const [root, ...path] = rawPath.split(PATH_SEPARATOR)
|
||||
|
||||
const node = (() => {
|
||||
// eslint-disable-next-line init-declarations
|
||||
let _node
|
||||
|
||||
if (root === '$gun') {
|
||||
_node = getGun()
|
||||
} else if (root === '$user') {
|
||||
const u = getUser()
|
||||
|
||||
if (!u.is) {
|
||||
throw new Error(Constants.ErrorCode.NOT_AUTH)
|
||||
}
|
||||
|
||||
_node = u
|
||||
} else {
|
||||
throw new TypeError(
|
||||
`Unknown kind of root, expected $gun or $user but got: ${root}`
|
||||
)
|
||||
}
|
||||
|
||||
for (const bit of path) {
|
||||
_node = _node.get(bit)
|
||||
}
|
||||
|
||||
return _node
|
||||
})()
|
||||
|
||||
const theValue = await deepEncryptIfNeeded(value)
|
||||
|
||||
if (Array.isArray(theValue)) {
|
||||
// we'll create a set of sets
|
||||
|
||||
const uuid = Utils.gunID()
|
||||
|
||||
// here we are simulating the top-most set()
|
||||
const subPath = rawPath + PATH_SEPARATOR + uuid
|
||||
|
||||
const writes = theValue.map(v => set(subPath, v))
|
||||
|
||||
await Promise.all(writes)
|
||||
|
||||
return uuid
|
||||
} else if (Schema.isObj(theValue)) {
|
||||
const uuid = Utils.gunID() // we'll handle UUID ourselves
|
||||
|
||||
// so we can use our own put()
|
||||
|
||||
const subPath = rawPath + PATH_SEPARATOR + uuid
|
||||
|
||||
await put(subPath, theValue)
|
||||
|
||||
return uuid
|
||||
}
|
||||
|
||||
/* else is primitive */
|
||||
|
||||
const id = await makePromise((res, rej) => {
|
||||
const subNode = node.set(theValue, ack => {
|
||||
if (
|
||||
ack.err &&
|
||||
typeof ack.err !== 'number' &&
|
||||
typeof ack.err !== 'object'
|
||||
) {
|
||||
rej(new Error(ack.err))
|
||||
} else {
|
||||
res(subNode._.get)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
return id
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
put,
|
||||
set,
|
||||
deepDecryptIfNeeded,
|
||||
deepEncryptIfNeeded
|
||||
}
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
import {Primitive} from '../contact-api/SimpleGUN'
|
||||
|
||||
|
||||
export interface RPCData {
|
||||
[K: string]: ValidRPCDataValue
|
||||
}
|
||||
|
||||
export type ValidRPCDataValue = Primitive | null | RPCData | Array<ValidRPCDataValue>
|
||||
|
|
@ -1,254 +0,0 @@
|
|||
/**
|
||||
* @format
|
||||
*/
|
||||
|
||||
const logger = require('../../../config/log')
|
||||
const Common = require('shock-common')
|
||||
const uuidv4 = require('uuid/v4')
|
||||
|
||||
const { getGun, getUser, isAuthenticated } = require('../Mediator')
|
||||
const { deepDecryptIfNeeded } = require('../rpc')
|
||||
const Subscriptions = require('./subscriptions')
|
||||
const GunActions = require('../../gunDB/contact-api/actions')
|
||||
const {
|
||||
encryptedEmit,
|
||||
encryptedOn,
|
||||
encryptedCallback
|
||||
} = require('../../../utils/ECC/socket')
|
||||
/// <reference path="../../../utils/GunSmith/Smith.ts" />
|
||||
|
||||
const ALLOWED_GUN_METHODS = [
|
||||
'map',
|
||||
'map.on',
|
||||
'on',
|
||||
'once',
|
||||
'load',
|
||||
'then',
|
||||
'open'
|
||||
]
|
||||
|
||||
/**
|
||||
* @typedef {import('../contact-api/SimpleGUN').ValidDataValue} ValidDataValue
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {(data: ValidDataValue, key?: string, _msg?: any, event?: any) => (void | Promise<void>)} GunListener
|
||||
* @typedef {{ reconnect: boolean, token: string }} SubscriptionOptions
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {string} root
|
||||
*/
|
||||
const getNode = root => {
|
||||
if (root === '$gun') {
|
||||
return getGun()
|
||||
}
|
||||
|
||||
if (root === '$user') {
|
||||
return getUser()
|
||||
}
|
||||
|
||||
return getGun().user(root)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Smith.GunSmithNode} node
|
||||
* @param {string} path
|
||||
*/
|
||||
const getGunQuery = (node, path) => {
|
||||
const bits = path.split('>')
|
||||
const query = bits.reduce((gunQuery, bit) => gunQuery.get(bit), node)
|
||||
return query
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a GunDB query call using the specified method
|
||||
* @param {any} query
|
||||
* @param {string} method
|
||||
* @param {GunListener} listener
|
||||
*/
|
||||
const executeGunQuery = (query, method, listener) => {
|
||||
if (!ALLOWED_GUN_METHODS.includes(method)) {
|
||||
throw {
|
||||
field: 'method',
|
||||
message: `Invalid GunDB method specified (${method}). `
|
||||
}
|
||||
}
|
||||
|
||||
if (method === 'on') {
|
||||
return query.on(listener)
|
||||
}
|
||||
|
||||
if (method === 'open') {
|
||||
return query.open(listener)
|
||||
}
|
||||
|
||||
if (method === 'map.on') {
|
||||
return query.map().on(listener)
|
||||
}
|
||||
|
||||
if (method === 'map.once') {
|
||||
return query.map().once(listener)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} queryData
|
||||
* @param {(eventName: string, ...args: any[]) => Promise<void>} queryData.emit
|
||||
* @param {string} queryData.publicKeyForDecryption
|
||||
* @param {string} queryData.subscriptionId
|
||||
* @param {string} queryData.deviceId
|
||||
* @param {string=} queryData.epubForDecryption
|
||||
* @param {string=} queryData.epubField If the epub is included in the received
|
||||
* data itself. Handshake requests for example, have an epub field.
|
||||
* @returns {GunListener}
|
||||
*/
|
||||
const queryListenerCallback = ({
|
||||
emit,
|
||||
publicKeyForDecryption,
|
||||
subscriptionId,
|
||||
deviceId,
|
||||
epubForDecryption,
|
||||
epubField
|
||||
}) => async (data, key, _msg, event) => {
|
||||
try {
|
||||
const subscription = Subscriptions.get({
|
||||
deviceId,
|
||||
subscriptionId
|
||||
})
|
||||
if (subscription && !subscription.unsubscribe && event) {
|
||||
Subscriptions.attachUnsubscribe({
|
||||
deviceId,
|
||||
subscriptionId,
|
||||
unsubscribe: () => event.off()
|
||||
})
|
||||
}
|
||||
const eventName = `query:data`
|
||||
if (publicKeyForDecryption?.length > 0 || epubForDecryption || epubField) {
|
||||
const decData = await deepDecryptIfNeeded(
|
||||
data,
|
||||
publicKeyForDecryption,
|
||||
(() => {
|
||||
if (epubField) {
|
||||
if (Common.isObj(data)) {
|
||||
const epub = data[epubField]
|
||||
if (Common.isPopulatedString(epub)) {
|
||||
return epub
|
||||
}
|
||||
|
||||
logger.error(
|
||||
`Got epubField in a rifle query, but the resulting value obtained is not an string -> `,
|
||||
{
|
||||
data,
|
||||
epub
|
||||
}
|
||||
)
|
||||
} else {
|
||||
logger.warn(
|
||||
`Got epubField in a rifle query for a non-object data -> `,
|
||||
{
|
||||
epubField,
|
||||
data
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
return epubForDecryption
|
||||
})()
|
||||
)
|
||||
emit(eventName, { subscriptionId, response: { data: decData, key } })
|
||||
return
|
||||
}
|
||||
|
||||
emit(eventName, { subscriptionId, response: { data, key } })
|
||||
} catch (err) {
|
||||
logger.error(`Error for gun rpc socket: ${err.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {import('socket.io').Socket} socket */
|
||||
const startSocket = socket => {
|
||||
try {
|
||||
const emit = encryptedEmit(socket)
|
||||
const on = encryptedOn(socket)
|
||||
const { encryptionId } = socket.handshake.auth
|
||||
|
||||
if (!isAuthenticated()) {
|
||||
logger.warn('GunDB is not yet authenticated')
|
||||
socket.emit(Common.Constants.ErrorCode.NOT_AUTH)
|
||||
}
|
||||
|
||||
if (isAuthenticated()) {
|
||||
socket.onAny(async () => {
|
||||
try {
|
||||
await GunActions.setLastSeenApp()
|
||||
} catch (err) {
|
||||
logger.info('error setting last seen app', err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
on('subscribe:query', (query, response) => {
|
||||
const { $shock, publicKey, epubForDecryption, epubField } = query
|
||||
const subscriptionId = uuidv4()
|
||||
try {
|
||||
if (!isAuthenticated()) {
|
||||
socket.emit(Common.Constants.ErrorCode.NOT_AUTH)
|
||||
return
|
||||
}
|
||||
|
||||
const [root, path, method] = $shock.split('::')
|
||||
const socketCallback = encryptedCallback(socket, response)
|
||||
|
||||
if (!ALLOWED_GUN_METHODS.includes(method)) {
|
||||
socketCallback(
|
||||
`Invalid method for gun rpc call: ${method}, query: ${$shock}`
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
Subscriptions.add({
|
||||
deviceId: encryptionId,
|
||||
subscriptionId
|
||||
})
|
||||
|
||||
const queryCallback = queryListenerCallback({
|
||||
emit,
|
||||
publicKeyForDecryption: publicKey,
|
||||
subscriptionId,
|
||||
deviceId: encryptionId,
|
||||
epubForDecryption,
|
||||
epubField
|
||||
})
|
||||
|
||||
socketCallback(null, {
|
||||
subscriptionId
|
||||
})
|
||||
|
||||
const node = getNode(root)
|
||||
const query = getGunQuery(node, path)
|
||||
|
||||
executeGunQuery(query, method, queryCallback)
|
||||
} catch (error) {
|
||||
emit(`query:error`, { subscriptionId, response: { data: error } })
|
||||
}
|
||||
})
|
||||
|
||||
on('unsubscribe', ({ subscriptionId }, response) => {
|
||||
const callback = encryptedCallback(socket, response)
|
||||
Subscriptions.remove({ deviceId: encryptionId, subscriptionId })
|
||||
callback(null, {
|
||||
message: 'Unsubscribed successfully!',
|
||||
success: true
|
||||
})
|
||||
})
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
Subscriptions.removeDevice({ deviceId: encryptionId })
|
||||
})
|
||||
} catch (err) {
|
||||
logger.error('GUNRPC: ' + err.message)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = startSocket
|
||||
|
|
@ -1,123 +0,0 @@
|
|||
/**
|
||||
* @typedef {() => void} Unsubscribe
|
||||
*/
|
||||
|
||||
/** @type {Map<string, Map<string, { subscriptionId: string, unsubscribe?: () => void, metadata?: object }>>} */
|
||||
const userSubscriptions = new Map()
|
||||
|
||||
/**
|
||||
* Adds a new Subscription
|
||||
* @param {Object} subscription
|
||||
* @param {string} subscription.deviceId
|
||||
* @param {string} subscription.subscriptionId
|
||||
* @param {(Unsubscribe)=} subscription.unsubscribe
|
||||
* @param {(object)=} subscription.metadata
|
||||
*/
|
||||
const add = ({ deviceId, subscriptionId, unsubscribe, metadata }) => {
|
||||
const deviceSubscriptions = userSubscriptions.get(deviceId)
|
||||
|
||||
const subscriptions = deviceSubscriptions ?? new Map()
|
||||
subscriptions.set(subscriptionId, {
|
||||
subscriptionId,
|
||||
unsubscribe,
|
||||
metadata
|
||||
})
|
||||
userSubscriptions.set(deviceId, subscriptions)
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a new Subscription
|
||||
* @param {Object} subscription
|
||||
* @param {string} subscription.deviceId
|
||||
* @param {string} subscription.subscriptionId
|
||||
* @param {Unsubscribe} subscription.unsubscribe
|
||||
*/
|
||||
const attachUnsubscribe = ({ deviceId, subscriptionId, unsubscribe }) => {
|
||||
const deviceSubscriptions = userSubscriptions.get(deviceId)
|
||||
|
||||
const subscriptions = deviceSubscriptions
|
||||
|
||||
if (!subscriptions) {
|
||||
return
|
||||
}
|
||||
|
||||
const subscription = subscriptions.get(subscriptionId)
|
||||
|
||||
if (!subscription) {
|
||||
return
|
||||
}
|
||||
|
||||
subscriptions.set(subscriptionId, {
|
||||
...subscription,
|
||||
unsubscribe
|
||||
})
|
||||
userSubscriptions.set(deviceId, subscriptions)
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsubscribes from a GunDB query
|
||||
* @param {Object} subscription
|
||||
* @param {string} subscription.deviceId
|
||||
* @param {string} subscription.subscriptionId
|
||||
*/
|
||||
const remove = ({ deviceId, subscriptionId }) => {
|
||||
const deviceSubscriptions = userSubscriptions.get(deviceId)
|
||||
|
||||
const subscriptions = deviceSubscriptions ?? new Map()
|
||||
const subscription = subscriptions.get(subscriptionId)
|
||||
|
||||
if (subscription?.unsubscribe) {
|
||||
subscription.unsubscribe()
|
||||
}
|
||||
|
||||
subscriptions.delete(subscriptionId)
|
||||
userSubscriptions.set(deviceId, subscriptions)
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsubscribes from all GunDB queries for a specific device
|
||||
* @param {Object} subscription
|
||||
* @param {string} subscription.deviceId
|
||||
*/
|
||||
const removeDevice = ({ deviceId }) => {
|
||||
const deviceSubscriptions = userSubscriptions.get(deviceId)
|
||||
|
||||
if (!deviceSubscriptions) {
|
||||
return
|
||||
}
|
||||
|
||||
Array.from(deviceSubscriptions.values()).map(subscription => {
|
||||
if (subscription && subscription.unsubscribe) {
|
||||
subscription.unsubscribe()
|
||||
}
|
||||
|
||||
return subscription
|
||||
})
|
||||
|
||||
userSubscriptions.set(deviceId, new Map())
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the specified subscription's info if it exists
|
||||
* @param {Object} subscription
|
||||
* @param {string} subscription.deviceId
|
||||
* @param {string} subscription.subscriptionId
|
||||
*/
|
||||
const get = ({ deviceId, subscriptionId }) => {
|
||||
const deviceSubscriptions = userSubscriptions.get(deviceId)
|
||||
|
||||
if (!deviceSubscriptions) {
|
||||
return false
|
||||
}
|
||||
|
||||
const subscription = deviceSubscriptions.get(subscriptionId)
|
||||
return subscription
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
add,
|
||||
attachUnsubscribe,
|
||||
get,
|
||||
remove,
|
||||
removeDevice
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
const API = require('./gunDB/contact-api')
|
||||
|
||||
module.exports.InitUserData = async (user) => {
|
||||
await API.Actions.setDisplayName('anon' + user._.sea.pub.slice(0, 8), user)
|
||||
await API.Actions.generateHandshakeAddress()
|
||||
await API.Actions.generateOrderAddress(user)
|
||||
await API.Actions.initWall()
|
||||
await API.Actions.setBio('A little bit about myself.', user)
|
||||
await API.Actions.setDefaultSeedProvider('', user)
|
||||
await API.Actions.setSeedServiceData('', user)
|
||||
await API.Actions.setCurrentStreamInfo('', user)
|
||||
}
|
||||
|
|
@ -1,134 +0,0 @@
|
|||
const Path = require("path");
|
||||
const grpc = require("@grpc/grpc-js");
|
||||
const protoLoader = require("@grpc/proto-loader");
|
||||
const logger = require("winston");
|
||||
const fs = require("../../utils/fs");
|
||||
const errorConstants = require("../../constants/errors");
|
||||
|
||||
// expose the routes to our app with module.exports
|
||||
/**
|
||||
* @typedef LightningConfig
|
||||
* @prop {string} lnrpcProtoPath
|
||||
* @prop {string} routerProtoPath
|
||||
* @prop {string} invoicesProtoPath
|
||||
* @prop {string} walletUnlockerProtoPath
|
||||
* @prop {string} lndHost
|
||||
* @prop {string} lndCertPath
|
||||
* @prop {string?} macaroonPath
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef LightningServices
|
||||
* @prop {any} lightning
|
||||
* @prop {any} walletUnlocker
|
||||
* @prop {any} router
|
||||
* @prop {any} invoices
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {LightningConfig} args0
|
||||
* @returns {Promise<LightningServices>}
|
||||
*/
|
||||
module.exports = async ({
|
||||
lnrpcProtoPath,
|
||||
routerProtoPath,
|
||||
invoicesProtoPath,
|
||||
walletUnlockerProtoPath,
|
||||
lndHost,
|
||||
lndCertPath,
|
||||
macaroonPath
|
||||
}) => {
|
||||
try {
|
||||
process.env.GRPC_SSL_CIPHER_SUITES = "HIGH+ECDSA";
|
||||
const protoLoaderConfig = {
|
||||
keepCase: true,
|
||||
longs: String,
|
||||
enums: String,
|
||||
defaults: true,
|
||||
oneofs: true,
|
||||
includeDirs: ["node_modules/google-proto-files", "proto", Path.resolve(__dirname, "../../config")]
|
||||
}
|
||||
|
||||
const [lnrpcProto, routerProto, walletUnlockerProto, invoicesProto] = await Promise.all([
|
||||
protoLoader.load(lnrpcProtoPath, protoLoaderConfig),
|
||||
protoLoader.load(routerProtoPath, protoLoaderConfig),
|
||||
protoLoader.load(walletUnlockerProtoPath, protoLoaderConfig),
|
||||
protoLoader.load(invoicesProtoPath, protoLoaderConfig)
|
||||
]);
|
||||
const { lnrpc } = grpc.loadPackageDefinition(lnrpcProto);
|
||||
const { routerrpc } = grpc.loadPackageDefinition(routerProto);
|
||||
const { invoicesrpc } = grpc.loadPackageDefinition(invoicesProto);
|
||||
const { lnrpc: walletunlockerrpc } = grpc.loadPackageDefinition(walletUnlockerProto);
|
||||
|
||||
const getCredentials = async () => {
|
||||
const lndCert = await fs.readFile(lndCertPath);
|
||||
const sslCreds = grpc.credentials.createSsl(lndCert);
|
||||
|
||||
if (macaroonPath) {
|
||||
const macaroonExists = await fs.access(macaroonPath);
|
||||
|
||||
if (macaroonExists) {
|
||||
const macaroonCreds = grpc.credentials.createFromMetadataGenerator(
|
||||
async (_, callback) => {
|
||||
const adminMacaroon = await fs.readFile(macaroonPath);
|
||||
const metadata = new grpc.Metadata();
|
||||
metadata.add("macaroon", adminMacaroon.toString("hex"));
|
||||
callback(null, metadata);
|
||||
}
|
||||
);
|
||||
return grpc.credentials.combineChannelCredentials(
|
||||
sslCreds,
|
||||
macaroonCreds
|
||||
);
|
||||
}
|
||||
|
||||
const error = errorConstants.MACAROON_PATH(macaroonPath);
|
||||
logger.error(error);
|
||||
throw error;
|
||||
} else {
|
||||
return sslCreds;
|
||||
}
|
||||
};
|
||||
|
||||
if (lndCertPath) {
|
||||
const certExists = await fs.access(lndCertPath);
|
||||
|
||||
if (certExists) {
|
||||
const credentials = await getCredentials();
|
||||
|
||||
// @ts-ignore
|
||||
const lightning = new lnrpc.Lightning(lndHost, credentials);
|
||||
// @ts-ignore
|
||||
const walletUnlocker = new walletunlockerrpc.WalletUnlocker(lndHost, credentials);
|
||||
// @ts-ignore
|
||||
const router = new routerrpc.Router(lndHost, credentials);
|
||||
// @ts-ignore
|
||||
const invoices = new invoicesrpc.Invoices(lndHost, credentials);
|
||||
return {
|
||||
lightning,
|
||||
walletUnlocker,
|
||||
router,
|
||||
invoices
|
||||
};
|
||||
}
|
||||
|
||||
const error = errorConstants.CERT_PATH(lndCertPath);
|
||||
logger.error(error);
|
||||
throw error;
|
||||
} else {
|
||||
const error = errorConstants.CERT_AND_MACAROON_MISSING(macaroonPath, lndCertPath);
|
||||
logger.error(error);
|
||||
throw error;
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error(err);
|
||||
if (err.code === 14) {
|
||||
throw {
|
||||
field: "unknown",
|
||||
message:
|
||||
"Failed to connect to LND server, make sure it's up and running."
|
||||
};
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
|
@ -1,601 +0,0 @@
|
|||
const Crypto = require('crypto')
|
||||
const logger = require('../../config/log')
|
||||
const Common = require('shock-common')
|
||||
const getGunUser = () => require('../gunDB/Mediator').getUser()
|
||||
const isAuthenticated = () => require('../gunDB/Mediator').isAuthenticated()
|
||||
const Key = require('../gunDB/contact-api/key')
|
||||
const lndV2 = require('../../utils/lightningServices/v2')
|
||||
/**
|
||||
* @typedef {import('../gunDB/contact-api/SimpleGUN').ISEA} ISEA
|
||||
* @typedef { 'spontaneousPayment' | 'tip' | 'torrentSeed' | 'contentReveal' | 'other'|'invoice'|'payment'|'chainTx' | 'streamSeed' |'service'|'product' } OrderType
|
||||
*
|
||||
* This represents a settled order only, unsettled orders have no coordinate
|
||||
* @typedef {object} CoordinateOrder //everything is optional for different types
|
||||
* @prop {string=} fromLndPub can be unknown when inbound
|
||||
* @prop {string=} toLndPub always known
|
||||
* @prop {string=} fromGunPub can be optional, if the payment/invoice is not related to an order
|
||||
* @prop {string=} toGunPub can be optional, if the payment/invoice is not related to an order
|
||||
* @prop {string=} fromBtcPub
|
||||
* @prop {string=} toBtcPub
|
||||
* @prop {boolean} inbound
|
||||
* NOTE: type specific checks are not made before creating the order node, filters must be done before rendering or processing
|
||||
*
|
||||
* @prop {string=} ownerGunPub Reserved for buddy system:
|
||||
* can be undefined, '', 'me', or node owner pub key to represent node owner,
|
||||
* otherwise it represents a buddy
|
||||
*
|
||||
* @prop {number} coordinateIndex can be payment_index, or add_index depending on if it's a payment or an invoice
|
||||
* @prop {string} coordinateHash can be payment_hash, or r_hash depending on if it's a payment or an invoice,
|
||||
* if it's a r_hash, must be hex encoded
|
||||
*
|
||||
* @prop {OrderType} type
|
||||
* @prop {number} amount
|
||||
* @prop {string=} description
|
||||
* @prop {string=} invoiceMemo
|
||||
* @prop {string=} metadata JSON encoded string to store extra data for special use cases
|
||||
* @prop {number=} timestamp timestamp will be added at processing time if empty
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {CoordinateOrder} order
|
||||
*/
|
||||
const checkOrderInfo = order => {
|
||||
const {
|
||||
fromLndPub,
|
||||
toLndPub,
|
||||
fromGunPub,
|
||||
toGunPub,
|
||||
fromBtcPub,
|
||||
toBtcPub,
|
||||
inbound,
|
||||
type,
|
||||
amount,
|
||||
description,
|
||||
coordinateIndex,
|
||||
coordinateHash,
|
||||
metadata,
|
||||
invoiceMemo
|
||||
} = order
|
||||
|
||||
if (fromLndPub && (typeof fromLndPub !== 'string' || fromLndPub === '')) {
|
||||
return 'invalid "fromLndPub" field provided to order coordinate'
|
||||
}
|
||||
if (toLndPub && (typeof toLndPub !== 'string' || toLndPub === '')) {
|
||||
return 'invalid or no "toLndPub" field provided to order coordinate'
|
||||
}
|
||||
if (fromGunPub && (typeof fromGunPub !== 'string' || fromGunPub === '')) {
|
||||
return 'invalid "fromGunPub" field provided to order coordinate'
|
||||
}
|
||||
if (toGunPub && (typeof toGunPub !== 'string' || toGunPub === '')) {
|
||||
return 'invalid "toGunPub" field provided to order coordinate'
|
||||
}
|
||||
if (fromBtcPub && (typeof fromBtcPub !== 'string' || fromBtcPub === '')) {
|
||||
return 'invalid "fromBtcPub" field provided to order coordinate'
|
||||
}
|
||||
if (toBtcPub && (typeof toBtcPub !== 'string' || toBtcPub === '')) {
|
||||
return 'invalid "toBtcPub" field provided to order coordinate'
|
||||
}
|
||||
if (typeof inbound !== 'boolean') {
|
||||
return 'invalid or no "inbound" field provided to order coordinate'
|
||||
}
|
||||
//@ts-expect-error
|
||||
if (typeof type !== 'string' || type === '') {
|
||||
return 'invalid or no "type" field provided to order coordinate'
|
||||
}
|
||||
if (typeof amount !== 'number') {
|
||||
return 'invalid or no "amount" field provided to order coordinate'
|
||||
}
|
||||
|
||||
if (typeof coordinateIndex !== 'number') {
|
||||
return 'invalid or no "coordinateIndex" field provided to order coordinate'
|
||||
}
|
||||
if (typeof coordinateHash !== 'string' || coordinateHash === '') {
|
||||
return 'invalid or no "coordinateHash" field provided to order coordinate'
|
||||
}
|
||||
|
||||
if (description && (typeof description !== 'string' || description === '')) {
|
||||
return 'invalid "description" field provided to order coordinate'
|
||||
}
|
||||
if (invoiceMemo && (typeof invoiceMemo !== 'string' || invoiceMemo === '')) {
|
||||
return 'invalid "invoiceMemo" field provided to order coordinate'
|
||||
}
|
||||
if (metadata && (typeof metadata !== 'string' || metadata === '')) {
|
||||
return 'invalid "metadata" field provided to order coordinate'
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/*
|
||||
*
|
||||
* @param {CoordinateOrder} orderInfo
|
||||
* @param {string} coordinateSHA256
|
||||
*//*
|
||||
const dateIndexCreateCb = (orderInfo, coordinateSHA256) => {
|
||||
//if (this.memIndex) { need bind to use this here
|
||||
//update date memIndex
|
||||
//}
|
||||
const date = new Date(orderInfo.timestamp || 0)
|
||||
//use UTC for consistency?
|
||||
const year = date.getUTCFullYear().toString()
|
||||
const month = date.getUTCMonth().toString()
|
||||
|
||||
getGunUser()
|
||||
.get(Key.DATE_COORDINATE_INDEX)
|
||||
.get(year)
|
||||
.get(month)
|
||||
.set(coordinateSHA256)
|
||||
}*/
|
||||
|
||||
/*
|
||||
* if not provided, assume current month and year
|
||||
* @param {number|null} year
|
||||
* @param {number|null} month
|
||||
*//*
|
||||
const getMonthCoordinates = async (year = null, month = null) => {
|
||||
const now = Date.now()
|
||||
const stringYear = year !== null ? year.toString() : now.getUTCFullYear().toString()
|
||||
const stringMonth = month !== null ? month.toString() : now.getUTCMonth().toString()
|
||||
|
||||
const data = await new Promise(res => {
|
||||
getGunUser()
|
||||
.get(Key.DATE_COORDINATE_INDEX)
|
||||
.get(stringYear)
|
||||
.get(stringMonth)
|
||||
.load(res)
|
||||
})
|
||||
const coordinatesArray = Object
|
||||
.values(data)
|
||||
.filter(coordinateSHA256 => typeof coordinateSHA256 === 'string')
|
||||
|
||||
return coordinatesArray
|
||||
}*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string|undefined} address
|
||||
* @param {CoordinateOrder} orderInfo
|
||||
*/
|
||||
const AddTmpChainOrder = async (address, orderInfo) => {
|
||||
if (!address) {
|
||||
throw new Error("invalid address passed to AddTmpChainOrder")
|
||||
}
|
||||
if (!orderInfo.toBtcPub) {
|
||||
throw new Error("invalid toBtcPub passed to AddTmpChainOrder")
|
||||
}
|
||||
const checkErr = checkOrderInfo(orderInfo)
|
||||
if (checkErr) {
|
||||
throw new Error(checkErr)
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {CoordinateOrder}
|
||||
*/
|
||||
const filteredOrder = {
|
||||
fromLndPub: orderInfo.fromLndPub,
|
||||
toLndPub: orderInfo.toLndPub,
|
||||
fromGunPub: orderInfo.fromGunPub,
|
||||
toGunPub: orderInfo.toGunPub,
|
||||
inbound: orderInfo.inbound,
|
||||
ownerGunPub: orderInfo.ownerGunPub,
|
||||
coordinateIndex: orderInfo.coordinateIndex,
|
||||
coordinateHash: orderInfo.coordinateHash,
|
||||
type: orderInfo.type,
|
||||
amount: orderInfo.amount,
|
||||
description: orderInfo.description,
|
||||
metadata: orderInfo.metadata,
|
||||
|
||||
timestamp: orderInfo.timestamp || Date.now(),
|
||||
}
|
||||
const orderString = JSON.stringify(filteredOrder)
|
||||
const mySecret = require('../gunDB/Mediator').getMySecret()
|
||||
const SEA = require('../gunDB/Mediator').mySEA
|
||||
const encryptedOrderString = await SEA.encrypt(orderString, mySecret)
|
||||
|
||||
const addressSHA256 = Crypto.createHash('SHA256')
|
||||
.update(address)
|
||||
.digest('hex')
|
||||
|
||||
await new Promise((res, rej) => {
|
||||
getGunUser()
|
||||
.get(Key.TMP_CHAIN_COORDINATE)
|
||||
.get(addressSHA256)
|
||||
.put(encryptedOrderString, ack => {
|
||||
if (ack.err && typeof ack.err !== 'number' && typeof ack.err !== 'object') {
|
||||
rej(
|
||||
new Error(
|
||||
`Error saving tmp chain coordinate order to user-graph: ${ack}`
|
||||
)
|
||||
)
|
||||
} else {
|
||||
res(null)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} address
|
||||
* @returns {Promise<false|CoordinateOrder>}
|
||||
*/
|
||||
const isTmpChainOrder = async (address) => {
|
||||
if (typeof address !== 'string' || address === '') {
|
||||
return false
|
||||
}
|
||||
const addressSHA256 = Crypto.createHash('SHA256')
|
||||
.update(address)
|
||||
.digest('hex')
|
||||
|
||||
const maybeData = await getGunUser()
|
||||
.get(Key.TMP_CHAIN_COORDINATE)
|
||||
.get(addressSHA256)
|
||||
.then()
|
||||
|
||||
if (typeof maybeData !== 'string' || maybeData === '') {
|
||||
return false
|
||||
}
|
||||
const mySecret = require('../gunDB/Mediator').getMySecret()
|
||||
const SEA = require('../gunDB/Mediator').mySEA
|
||||
const decryptedString = await SEA.decrypt(maybeData, mySecret)
|
||||
if (typeof decryptedString !== 'string' || decryptedString === '') {
|
||||
return false
|
||||
}
|
||||
|
||||
const tmpOrder = JSON.parse(decryptedString)
|
||||
const checkErr = checkOrderInfo(tmpOrder)
|
||||
if (checkErr) {
|
||||
return false
|
||||
}
|
||||
|
||||
return tmpOrder
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} address
|
||||
*/
|
||||
const clearTmpChainOrder = async (address) => {
|
||||
if (typeof address !== 'string' || address === '') {
|
||||
return
|
||||
}
|
||||
const addressSHA256 = Crypto.createHash('SHA256')
|
||||
.update(address)
|
||||
.digest('hex')
|
||||
|
||||
await new Promise((res, rej) => {
|
||||
getGunUser()
|
||||
.get(Key.TMP_CHAIN_COORDINATE)
|
||||
.get(addressSHA256)
|
||||
.put(null, ack => {
|
||||
if (ack.err && typeof ack.err !== 'number' && typeof ack.err !== 'object') {
|
||||
rej(
|
||||
new Error(
|
||||
`Error nulling tmp chain coordinate order to user-graph: ${ack}`
|
||||
)
|
||||
)
|
||||
} else {
|
||||
res(null)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Common.Schema.ChainTransaction} tx
|
||||
* @param {CoordinateOrder|false| undefined} order
|
||||
*/
|
||||
const handleUnconfirmedTx = (tx, order) => {
|
||||
const { tx_hash } = tx
|
||||
const amountInt = parseInt(tx.amount, 10)
|
||||
if (order) {
|
||||
/*if an order already exists, update the order data
|
||||
if an unconfirmed transaction has a tmp order already
|
||||
it means the address was generated by shockAPI, or the tx was sent by shockAPI*/
|
||||
const orderUpdate = order
|
||||
orderUpdate.amount = Math.abs(amountInt)
|
||||
orderUpdate.inbound = amountInt > 0
|
||||
/*tmp coordinate does not have a coordinate hash until the transaction is created,
|
||||
before it will contain 'unknown' */
|
||||
orderUpdate.coordinateHash = tx_hash
|
||||
/*update the order data,
|
||||
provides a notification when the TX enters the mempool */
|
||||
AddTmpChainOrder(orderUpdate.toBtcPub, orderUpdate)
|
||||
} else {
|
||||
/*if an order does not exist, create the tmp order,
|
||||
and use tx_hash as key.
|
||||
this means the address was NOT generated by shockAPI, or the tx was NOT sent by shockAPI */
|
||||
AddTmpChainOrder(tx_hash, {
|
||||
type: 'chainTx',
|
||||
amount: Math.abs(amountInt),
|
||||
coordinateHash: tx_hash,
|
||||
coordinateIndex: 0, //coordinate index is 0 until the tx is confirmed and the block is known
|
||||
inbound: amountInt > 0,
|
||||
toBtcPub: 'unknown'
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class SchemaManager {
|
||||
//constructor() {
|
||||
// this.orderCreateIndexCallbacks.push(dateIndexCreateCb) //create more Cbs and put them here for more indexes callbacks
|
||||
//}
|
||||
|
||||
//dateIndexName = 'dateIndex'
|
||||
/**
|
||||
* @type {((order : CoordinateOrder,coordinateSHA256 : string)=>void)[]}
|
||||
*/
|
||||
orderCreateIndexCallbacks = []
|
||||
|
||||
/**
|
||||
* @param {CoordinateOrder} orderInfo
|
||||
*/
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
async AddOrder(orderInfo) {
|
||||
const checkErr = checkOrderInfo(orderInfo)
|
||||
if (checkErr) {
|
||||
throw new Error(checkErr)
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {CoordinateOrder}
|
||||
*/
|
||||
const filteredOrder = {
|
||||
fromLndPub: orderInfo.fromLndPub,
|
||||
toLndPub: orderInfo.toLndPub,
|
||||
fromGunPub: orderInfo.fromGunPub,
|
||||
toGunPub: orderInfo.toGunPub,
|
||||
inbound: orderInfo.inbound,
|
||||
ownerGunPub: orderInfo.ownerGunPub,
|
||||
coordinateIndex: orderInfo.coordinateIndex,
|
||||
coordinateHash: orderInfo.coordinateHash,
|
||||
type: orderInfo.type,
|
||||
amount: orderInfo.amount,
|
||||
description: orderInfo.description,
|
||||
metadata: orderInfo.metadata,
|
||||
timestamp: orderInfo.timestamp || Date.now(),
|
||||
}
|
||||
const orderString = JSON.stringify(filteredOrder)
|
||||
const mySecret = require('../gunDB/Mediator').getMySecret()
|
||||
const SEA = require('../gunDB/Mediator').mySEA
|
||||
const encryptedOrderString = await SEA.encrypt(orderString, mySecret)
|
||||
const coordinatePub = filteredOrder.inbound ? filteredOrder.toLndPub : filteredOrder.fromLndPub
|
||||
const coordinate = `${coordinatePub}__${filteredOrder.coordinateIndex}__${filteredOrder.coordinateHash}`
|
||||
const coordinateSHA256 = Crypto.createHash('SHA256')
|
||||
.update(coordinate)
|
||||
.digest('hex')
|
||||
await new Promise((res, rej) => {
|
||||
getGunUser()
|
||||
.get(Key.COORDINATES)
|
||||
.get(coordinateSHA256)
|
||||
.put(encryptedOrderString, ack => {
|
||||
if (ack.err && typeof ack.err !== 'number' && typeof ack.err !== 'object') {
|
||||
logger.info(ack)
|
||||
rej(
|
||||
new Error(
|
||||
`Error saving coordinate order to user-graph: ${ack}`
|
||||
)
|
||||
)
|
||||
} else {
|
||||
res(null)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
//update all indexes with
|
||||
//this.orderCreateIndexCallbacks.forEach(cb => cb(filteredOrder, coordinateSHA256))
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* if not provided, assume current month and year
|
||||
* @param {number|null} year
|
||||
* @param {number|null} month
|
||||
* @returns {Promise<CoordinateOrder[]>} from newer to older
|
||||
*//*
|
||||
async getMonthOrders(year = null, month = null) {
|
||||
const now = new Date()
|
||||
const intYear = year !== null ? year : now.getUTCFullYear()
|
||||
const intMonth = month !== null ? month : now.getUTCMonth()
|
||||
|
||||
let coordinates = null
|
||||
if (this.memIndex) {
|
||||
//get coordinates from this.memDateIndex
|
||||
} else {
|
||||
coordinates = await getMonthCoordinates(intYear, intMonth)
|
||||
}
|
||||
const orders = []
|
||||
if (!coordinates) {
|
||||
return orders
|
||||
}
|
||||
await Common.Utils.asyncForEach(coordinates, async coordinateSHA256 => {
|
||||
const encryptedOrderString = await getGunUser()
|
||||
.get(Key.COORDINATES)
|
||||
.get(coordinateSHA256)
|
||||
.then()
|
||||
if (typeof encryptedOrderString !== 'string') {
|
||||
return
|
||||
}
|
||||
const mySecret = require('../gunDB/Mediator').getMySecret()
|
||||
const SEA = require('../gunDB/Mediator').mySEA
|
||||
const decryptedString = await SEA.decrypt(encryptedOrderString, mySecret)
|
||||
const orderJSON = JSON.parse(decryptedString)
|
||||
orders.push(orderJSON)
|
||||
})
|
||||
const orderedOrders = orders.sort((a, b) => b.timestamp - a.timestamp)
|
||||
return orderedOrders
|
||||
}*/
|
||||
|
||||
/**
|
||||
* @typedef {Common.Schema.InvoiceWhenListed & {r_hash:Buffer,payment_addr:Buffer}} Invoice
|
||||
*/
|
||||
/**
|
||||
* @type {Record<string,(invoice:Invoice) =>void>}
|
||||
*/
|
||||
_listeningInvoices = {}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Buffer} r_hash
|
||||
* @param {(invoice:Invoice) =>void} done
|
||||
*/
|
||||
addListenInvoice(r_hash, done) {
|
||||
const hashString = r_hash.toString("hex")
|
||||
this._listeningInvoices[hashString] = done
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Common.Schema.InvoiceWhenListed & {r_hash:Buffer,payment_addr:Buffer}} data
|
||||
*/
|
||||
invoiceStreamDataCb(data) {
|
||||
if (!data.settled) {
|
||||
//invoice not paid yet
|
||||
return
|
||||
}
|
||||
const hashString = data.r_hash.toString('hex')
|
||||
const amt = parseInt(data.amt_paid_sat, 10)
|
||||
if (this._listeningInvoices[hashString]) {
|
||||
const done = this._listeningInvoices[hashString]
|
||||
delete this._listeningInvoices[hashString]
|
||||
done(data)
|
||||
} else {
|
||||
this.AddOrder({
|
||||
type: 'invoice',
|
||||
coordinateHash: hashString,
|
||||
coordinateIndex: parseInt(data.add_index, 10),
|
||||
inbound: true,
|
||||
amount: amt,
|
||||
toLndPub: data.payment_addr.toString('hex'),
|
||||
invoiceMemo: data.memo
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @type {Record<string,boolean>}
|
||||
* lnd fires a confirmed transaction event TWICE, let's make sure it is only managed ONCE
|
||||
*/
|
||||
_confirmedTransactions = {}
|
||||
|
||||
/**
|
||||
* @param {Common.Schema.ChainTransaction} data
|
||||
*/
|
||||
async transactionStreamDataCb(data) {
|
||||
const { num_confirmations } = data
|
||||
const responses = await Promise.all(data.dest_addresses.map(isTmpChainOrder))
|
||||
const hasOrder = responses.find(res => res !== false)
|
||||
|
||||
if (num_confirmations === 0) {
|
||||
handleUnconfirmedTx(data, hasOrder)
|
||||
} else {
|
||||
this.handleConfirmedTx(data, hasOrder)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Common.Schema.ChainTransaction} tx
|
||||
* @param {CoordinateOrder|false| undefined} order
|
||||
*/
|
||||
handleConfirmedTx(tx, order) {
|
||||
const { tx_hash } = tx
|
||||
if (this._confirmedTransactions[tx_hash]) {
|
||||
//this tx confirmation was already handled
|
||||
return
|
||||
}
|
||||
if (!order) {
|
||||
/*confirmed transaction MUST have a tmp order,
|
||||
if not, means something gone wrong */
|
||||
logger.error('found a confirmed transaction that does not have a tmp order!!')
|
||||
return
|
||||
}
|
||||
if (!order.toBtcPub) {
|
||||
/*confirmed transaction tmp order MUST have a non null toBtcPub */
|
||||
logger.error('found a confirmed transaction that does not have toBtcPub in the order!!')
|
||||
return
|
||||
}
|
||||
const finalOrder = order
|
||||
finalOrder.coordinateIndex = tx.block_height
|
||||
this.AddOrder(finalOrder)
|
||||
if (order.toBtcPub === 'unknown') {
|
||||
clearTmpChainOrder(tx_hash)
|
||||
} else {
|
||||
clearTmpChainOrder(order.toBtcPub)
|
||||
}
|
||||
this._confirmedTransactions[tx_hash] = true
|
||||
}
|
||||
}
|
||||
|
||||
const Manager = new SchemaManager()
|
||||
/*invoice stream,
|
||||
this is the only place where it's needed,
|
||||
everything is a coordinate now*/
|
||||
let InvoiceShouldRetry = true
|
||||
setInterval(() => {
|
||||
if (!InvoiceShouldRetry) {
|
||||
return
|
||||
}
|
||||
if (!isAuthenticated()) {
|
||||
return
|
||||
}
|
||||
InvoiceShouldRetry = false
|
||||
|
||||
lndV2.subscribeInvoices(
|
||||
invoice => {
|
||||
if (!isAuthenticated) {
|
||||
logger.error("got an invoice while not authenticated, will ignore it and cancel the stream")
|
||||
return true
|
||||
}
|
||||
Manager.invoiceStreamDataCb(invoice)
|
||||
return false
|
||||
},
|
||||
error => {
|
||||
logger.error(`Error in invoices sub, will retry in two second, reason: ${error.reason}`)
|
||||
InvoiceShouldRetry = true
|
||||
}
|
||||
)
|
||||
|
||||
}, 2000)
|
||||
|
||||
/*transactions stream,
|
||||
this is the only place where it's needed,
|
||||
everything is a coordinate now*/
|
||||
let TransactionShouldRetry = true
|
||||
setInterval(() => {
|
||||
if (!TransactionShouldRetry) {
|
||||
return
|
||||
}
|
||||
if (!isAuthenticated()) {
|
||||
return
|
||||
}
|
||||
TransactionShouldRetry = false
|
||||
|
||||
lndV2.subscribeTransactions(
|
||||
transaction => {
|
||||
if (!isAuthenticated) {
|
||||
logger.error("got a transaction while not authenticated, will ignore it and cancel the stream")
|
||||
return true
|
||||
}
|
||||
Manager.transactionStreamDataCb(transaction)
|
||||
return false
|
||||
},
|
||||
error => {
|
||||
logger.error(`Error in transaction sub, will retry in two second, reason: ${error.reason}`)
|
||||
TransactionShouldRetry = true
|
||||
}
|
||||
)
|
||||
|
||||
}, 2000)
|
||||
|
||||
module.exports = Manager
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
const crypto = require('crypto')
|
||||
const fetch = require('node-fetch')
|
||||
|
||||
const selfContentToken = () => {
|
||||
const seedUrl = process.env.TORRENT_SEED_URL
|
||||
const seedToken = process.env.TORRENT_SEED_TOKEN
|
||||
if (!seedUrl || !seedToken) {
|
||||
return false
|
||||
}
|
||||
return {seedUrl,seedToken}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {number} nOfTokens
|
||||
* @param {{seedUrl:string,seedToken:string}} param1
|
||||
* @returns
|
||||
*/
|
||||
const enrollContentTokens = async (nOfTokens,{seedUrl,seedToken}) => {
|
||||
const tokens = Array(nOfTokens)
|
||||
for (let i = 0; i < nOfTokens; i++) {
|
||||
tokens[i] = crypto.randomBytes(32).toString('hex')
|
||||
}
|
||||
/**@param {string} token */
|
||||
const enrollToken = async token => {
|
||||
const reqData = {
|
||||
seed_token: seedToken,
|
||||
wallet_token: token
|
||||
}
|
||||
//@ts-expect-error
|
||||
const res = await fetch(`${seedUrl}/api/enroll_token`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(reqData)
|
||||
})
|
||||
if (res.status !== 200) {
|
||||
throw new Error('torrentSeed service currently not available')
|
||||
}
|
||||
}
|
||||
await Promise.all(tokens.map(enrollToken))
|
||||
return tokens
|
||||
}
|
||||
|
||||
|
||||
|
||||
module.exports = {
|
||||
selfContentToken,
|
||||
enrollContentTokens
|
||||
}
|
||||
|
|
@ -1,150 +0,0 @@
|
|||
|
||||
const EventEmitter = require('events')
|
||||
const fetch = require('node-fetch')
|
||||
const Key = require('./gunDB/contact-api/key')
|
||||
const StreamLiveManager = new EventEmitter()
|
||||
|
||||
const startedStream = (data) => {
|
||||
StreamLiveManager.emit('awaitStream',data)
|
||||
}
|
||||
const endStream = (data) => {
|
||||
StreamLiveManager.emit('endStream',data)
|
||||
}
|
||||
module.exports = {startedStream,endStream}
|
||||
|
||||
//-----------------------------------------
|
||||
|
||||
const intervalsWaitingAlive = {}
|
||||
const intervalsStreamingViewers = {}
|
||||
const intervalsWaitingMp4 = {}
|
||||
|
||||
const clearStreamInterval = (postId, map) => {
|
||||
if(!postId){
|
||||
return
|
||||
}
|
||||
if(map === "intervalsWaitingAlive"){
|
||||
if(!intervalsWaitingAlive[postId]){
|
||||
return
|
||||
}
|
||||
clearInterval(intervalsWaitingAlive[postId])
|
||||
delete intervalsWaitingAlive[postId]
|
||||
}
|
||||
if(map === "intervalsStreamingViewers"){
|
||||
if(!intervalsStreamingViewers[postId]){
|
||||
return
|
||||
}
|
||||
clearInterval(intervalsStreamingViewers[postId])
|
||||
delete intervalsStreamingViewers[postId]
|
||||
}
|
||||
if(map === "intervalsWaitingMp4"){
|
||||
if(!intervalsWaitingMp4[postId]){
|
||||
return
|
||||
}
|
||||
clearInterval(intervalsWaitingMp4[postId])
|
||||
delete intervalsWaitingMp4[postId]
|
||||
}
|
||||
}
|
||||
|
||||
StreamLiveManager.on('awaitStream', data => {
|
||||
const { postId, contentId, statusUrl } = data
|
||||
if(intervalsWaitingAlive[postId]){
|
||||
clearStreamInterval(intervalsWaitingAlive[postId])
|
||||
}
|
||||
const user = require('../services/gunDB/Mediator').getUser()
|
||||
intervalsWaitingAlive[postId] = setInterval(async () => {
|
||||
try {
|
||||
const res = await fetch(statusUrl)
|
||||
const j = await res.json()
|
||||
if (!j.isLive) {
|
||||
return
|
||||
}
|
||||
user
|
||||
.get(Key.POSTS_NEW)
|
||||
.get(postId)
|
||||
.get('contentItems')
|
||||
.get(contentId)
|
||||
.get('liveStatus')
|
||||
.put('live')
|
||||
clearStreamInterval(postId,"intervalsWaitingAlive")
|
||||
StreamLiveManager.emit('followStream', data)
|
||||
//eslint-disable-next-line no-empty
|
||||
} catch{}
|
||||
}, 2 * 1000)
|
||||
//kill sub after 10 minutes
|
||||
setTimeout(()=>{
|
||||
clearStreamInterval(postId,"intervalsWaitingAlive")
|
||||
},10 * 60 * 1000)
|
||||
})
|
||||
|
||||
StreamLiveManager.on('followStream', data => {
|
||||
const { postId, contentId, statusUrl } = data
|
||||
if(intervalsStreamingViewers[postId]){
|
||||
clearStreamInterval(postId,"intervalsStreamingViewers")
|
||||
}
|
||||
const user = require('../services/gunDB/Mediator').getUser()
|
||||
intervalsStreamingViewers[postId] = setInterval(async () => {
|
||||
try {
|
||||
const res = await fetch(statusUrl)
|
||||
const j = await res.json()
|
||||
if (typeof j.viewers !== 'number') {
|
||||
return
|
||||
}
|
||||
user
|
||||
.get(Key.POSTS_NEW)
|
||||
.get(postId)
|
||||
.get('contentItems')
|
||||
.get(contentId)
|
||||
.get('viewersCounter')
|
||||
.put(j.viewers)
|
||||
//eslint-disable-next-line no-empty
|
||||
} catch{}
|
||||
}, 5 * 1000)
|
||||
})
|
||||
|
||||
StreamLiveManager.on('endStream', data => {
|
||||
const { postId, contentId, endUrl, urlForMagnet, obsToken } = data
|
||||
console.log("ending stream!")
|
||||
clearStreamInterval(postId,"intervalsStreamingViewers")
|
||||
if(intervalsWaitingMp4[postId]){
|
||||
clearStreamInterval(postId,"intervalsWaitingMp4")
|
||||
}
|
||||
const user = require('../services/gunDB/Mediator').getUser()
|
||||
user
|
||||
.get(Key.POSTS_NEW)
|
||||
.get(postId)
|
||||
.get('contentItems')
|
||||
.get(contentId)
|
||||
.get('liveStatus')
|
||||
.put('waiting')
|
||||
fetch(endUrl,{
|
||||
headers: {
|
||||
'Authorization': `Bearer ${obsToken}`
|
||||
},
|
||||
})
|
||||
intervalsWaitingMp4[postId] = setInterval(async () => {
|
||||
try {
|
||||
const res = await fetch(urlForMagnet)
|
||||
const j = await res.json()
|
||||
if (!j.magnet) {
|
||||
return
|
||||
}
|
||||
user
|
||||
.get(Key.POSTS_NEW)
|
||||
.get(postId)
|
||||
.get('contentItems')
|
||||
.get(contentId)
|
||||
.get('liveStatus')
|
||||
.put('wasLive')
|
||||
user
|
||||
.get(Key.POSTS_NEW)
|
||||
.get(postId)
|
||||
.get('contentItems')
|
||||
.get(contentId)
|
||||
.get('playbackMagnet')
|
||||
.put(j.magnet)
|
||||
clearStreamInterval(postId,"intervalsWaitingMp4")
|
||||
//eslint-disable-next-line no-empty
|
||||
} catch{}
|
||||
}, 5 * 1000)
|
||||
})
|
||||
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
//@ts-nocheck TODO- fix types
|
||||
const { gunUUID } = require("../utils")
|
||||
const logger = require('../config/log')
|
||||
class TipsCB {
|
||||
listeners = {}
|
||||
|
||||
postsEnabled = {}
|
||||
|
||||
enablePostNotifications(postID){
|
||||
const accessId = gunUUID()
|
||||
this.postsEnabled[accessId] = postID
|
||||
return accessId
|
||||
}
|
||||
|
||||
addSocket(accessId,socket){
|
||||
if(!this.postsEnabled[accessId]){
|
||||
return "invalid access id"
|
||||
}
|
||||
const postID = this.postsEnabled[accessId]
|
||||
logger.info("subbing new socket for post: "+postID)
|
||||
|
||||
if(!this.listeners[postID]){
|
||||
this.listeners[postID] = []
|
||||
}
|
||||
this.listeners[postID].push(socket)
|
||||
}
|
||||
|
||||
notifySocketIfAny(postID,name,message,amount){
|
||||
if(!this.listeners[postID]){
|
||||
return
|
||||
}
|
||||
this.listeners[postID].forEach(socket => {
|
||||
if(!socket.connected){
|
||||
return
|
||||
}
|
||||
socket.emit("update",{
|
||||
name,message,amount
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const TipsForwarder = new TipsCB()
|
||||
module.exports = TipsForwarder
|
||||
|
|
@ -1,109 +0,0 @@
|
|||
/**
|
||||
* @format
|
||||
*/
|
||||
import Gun from 'gun'
|
||||
import uuid from 'uuid/v1'
|
||||
|
||||
import { mySEA } from '../../services/gunDB/Mediator'
|
||||
import { UserGUNNode } from '../../services/gunDB/contact-api/SimpleGUN'
|
||||
|
||||
const setupUser = async (): Promise<[UserGUNNode]> => {
|
||||
const gun = Gun({
|
||||
file: 'GUN-TEST-' + uuid()
|
||||
})
|
||||
|
||||
const user = (gun.user() as unknown) as UserGUNNode
|
||||
|
||||
await new Promise<void>((res, rej) => {
|
||||
user.create('testAlias-' + uuid(), 'testPass', ack => {
|
||||
if (typeof ack.err === 'string') {
|
||||
rej(new Error(ack.err))
|
||||
} else {
|
||||
res()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
return [user]
|
||||
}
|
||||
|
||||
const encryptsDecryptsStrings = async () => {
|
||||
const [user] = await setupUser()
|
||||
|
||||
const stringMessage = 'Lorem ipsum dolor'
|
||||
|
||||
const sec = await mySEA.secret(user._.sea.epub, user._.sea)
|
||||
const encrypted = await mySEA.encrypt(stringMessage, sec)
|
||||
const decrypted = await mySEA.decrypt(encrypted, sec)
|
||||
|
||||
if (decrypted !== stringMessage) {
|
||||
throw new Error()
|
||||
}
|
||||
}
|
||||
|
||||
const encryptsDecryptsBooleans = async () => {
|
||||
const [user] = await setupUser()
|
||||
|
||||
const truth = true
|
||||
const lie = false
|
||||
|
||||
const sec = await mySEA.secret(user._.sea.epub, user._.sea)
|
||||
|
||||
const encryptedTruth = await mySEA.encrypt(truth, sec)
|
||||
const decryptedTruth = await mySEA.decryptBoolean(encryptedTruth, sec)
|
||||
|
||||
if (decryptedTruth !== truth) {
|
||||
throw new Error()
|
||||
}
|
||||
|
||||
const encryptedLie = await mySEA.encrypt(lie, sec)
|
||||
const decryptedLie = await mySEA.decryptBoolean(encryptedLie, sec)
|
||||
|
||||
if (decryptedLie !== lie) {
|
||||
throw new Error(
|
||||
`Expected false got: ${decryptedLie} - ${typeof decryptedLie}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const encryptsDecryptsNumbers = async () => {
|
||||
const [user] = await setupUser()
|
||||
|
||||
const number = Math.random() * 999999
|
||||
|
||||
const sec = await mySEA.secret(user._.sea.epub, user._.sea)
|
||||
const encrypted = await mySEA.encrypt(number, sec)
|
||||
const decrypted = await mySEA.decryptNumber(encrypted, sec)
|
||||
|
||||
if (decrypted !== number) {
|
||||
throw new Error()
|
||||
}
|
||||
}
|
||||
|
||||
const encryptsDecryptsZero = async () => {
|
||||
const [user] = await setupUser()
|
||||
|
||||
const zero = 0
|
||||
|
||||
const sec = await mySEA.secret(user._.sea.epub, user._.sea)
|
||||
const encrypted = await mySEA.encrypt(zero, sec)
|
||||
const decrypted = await mySEA.decryptNumber(encrypted, sec)
|
||||
|
||||
if (decrypted !== zero) {
|
||||
throw new Error()
|
||||
}
|
||||
}
|
||||
|
||||
const runAllTests = async () => {
|
||||
await encryptsDecryptsStrings()
|
||||
await encryptsDecryptsBooleans()
|
||||
await encryptsDecryptsNumbers()
|
||||
await encryptsDecryptsZero()
|
||||
|
||||
console.log('\n--------------------------------')
|
||||
console.log('All tests ran successfully')
|
||||
console.log('--------------------------------\n')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
runAllTests()
|
||||
12
src/auth.ts
Normal file
12
src/auth.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { ServerOptions } from "../proto/autogenerated/ts/express_server";
|
||||
import Main from './services/main'
|
||||
const serverOptions = (mainHandler: Main): ServerOptions => {
|
||||
return {
|
||||
AdminAuthGuard: async (authHeader) => { console.log("admin auth login with header: " + authHeader); return { admin_id: "__Admin__" } },
|
||||
UserAuthGuard: async (authHeader) => { return { user_id: mainHandler.DecodeUserToken(authHeader) } },
|
||||
GuestAuthGuard: async (_) => ({}),
|
||||
encryptCallback: async (_, b) => b,
|
||||
decryptCallback: async (_, b) => b,
|
||||
}
|
||||
}
|
||||
export default serverOptions
|
||||
19
src/cors.js
19
src/cors.js
|
|
@ -1,19 +0,0 @@
|
|||
const setAccessControlHeaders = (req, res) => {
|
||||
res.header("Access-Control-Allow-Origin", "*");
|
||||
res.header("Access-Control-Allow-Methods", "OPTIONS,POST,GET,PUT,DELETE")
|
||||
res.header(
|
||||
"Access-Control-Allow-Headers",
|
||||
"Origin, X-Requested-With, Content-Type, Accept, Authorization, public-key-for-decryption, encryption-device-id, public-key-for-decryption,x-shock-hybrid-relay-id-x"
|
||||
);
|
||||
};
|
||||
|
||||
module.exports = (req, res, next) => {
|
||||
if (req.method === "OPTIONS") {
|
||||
setAccessControlHeaders(req, res);
|
||||
res.sendStatus(204);
|
||||
return;
|
||||
}
|
||||
|
||||
setAccessControlHeaders(req, res);
|
||||
next();
|
||||
};
|
||||
59
src/index.spec.ts
Normal file
59
src/index.spec.ts
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import 'dotenv/config' // TODO - test env
|
||||
import { AfterAll, BeforeAll, expect, FTest, Test, TestSuite } from 'testyts';
|
||||
import NewServer from '../proto/autogenerated/ts/express_server'
|
||||
import NewClient from '../proto/autogenerated/ts/http_client'
|
||||
import methods from './services/serverMethods';
|
||||
import serverOptions from './auth';
|
||||
import GetServerMethods from './services/serverMethods'
|
||||
import Main, { LoadMainSettingsFromEnv } from './services/main'
|
||||
import * as Types from '../proto/autogenerated/ts/types';
|
||||
const testPort = 4000
|
||||
|
||||
@TestSuite()
|
||||
export class ServerTestSuite {
|
||||
userAuthHeader = ""
|
||||
client = NewClient({
|
||||
baseUrl: `http://localhost:${testPort}`,
|
||||
retrieveAdminAuth: async () => (""),
|
||||
retrieveGuestAuth: async () => (""),
|
||||
retrieveUserAuth: async () => this.userAuthHeader,
|
||||
decryptCallback: async (b) => b,
|
||||
encryptCallback: async (b) => b,
|
||||
deviceId: "device0"
|
||||
})
|
||||
mainHandler = new Main(LoadMainSettingsFromEnv()) // TODO - test env file
|
||||
server = NewServer(GetServerMethods(this.mainHandler), { ...serverOptions(this.mainHandler), throwErrors: true })
|
||||
|
||||
|
||||
@BeforeAll()
|
||||
async startServer() {
|
||||
await this.mainHandler.storage.Connect()
|
||||
this.server.Listen(testPort)
|
||||
}
|
||||
@AfterAll()
|
||||
stopServer() {
|
||||
this.server.Close()
|
||||
}
|
||||
@Test()
|
||||
async health() {
|
||||
await this.client.Health()
|
||||
}
|
||||
|
||||
@Test()
|
||||
async getInfo() {
|
||||
console.log(await this.client.LndGetInfo({ node_id: 0 }))
|
||||
}
|
||||
@Test()
|
||||
async createUser() {
|
||||
const res = await this.client.AddUser({ name: "test", callback_url: "http://...", secret: "shhhhhht" })
|
||||
if (res.status === 'ERROR') throw new Error(res.reason)
|
||||
console.log(res.result)
|
||||
const user = await this.mainHandler.storage.GetUser(res.result.user_id)
|
||||
console.log(user)
|
||||
this.userAuthHeader = res.result.auth_token
|
||||
}
|
||||
@Test()
|
||||
async newAddress() {
|
||||
console.log(await this.client.NewAddress({ address_type: Types.AddressType.WITNESS_PUBKEY_HASH }))
|
||||
}
|
||||
}
|
||||
11
src/index.ts
Normal file
11
src/index.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import 'dotenv/config'
|
||||
import NewServer from '../proto/autogenerated/ts/express_server'
|
||||
import GetServerMethods from './services/serverMethods'
|
||||
import serverOptions from './auth';
|
||||
import Main, { LoadMainSettingsFromEnv } from './services/main'
|
||||
(async () => {
|
||||
const mainHandler = new Main(LoadMainSettingsFromEnv())
|
||||
await mainHandler.storage.Connect()
|
||||
const Server = NewServer(GetServerMethods(mainHandler), serverOptions(mainHandler))
|
||||
Server.Listen(3000)
|
||||
})()
|
||||
2669
src/routes.js
2669
src/routes.js
File diff suppressed because it is too large
Load diff
439
src/server.js
439
src/server.js
|
|
@ -1,439 +0,0 @@
|
|||
/**
|
||||
* @prettier
|
||||
*/
|
||||
// @ts-check
|
||||
|
||||
const ECCrypto = require('eccrypto')
|
||||
|
||||
const ECC = require('../utils/ECC')
|
||||
|
||||
/**
|
||||
* This API run's private key.
|
||||
*/
|
||||
const runPrivateKey = ECCrypto.generatePrivate()
|
||||
/**
|
||||
* This API run's public key.
|
||||
*/
|
||||
const runPublicKey = ECCrypto.getPublic(runPrivateKey)
|
||||
|
||||
process.on('uncaughtException', e => {
|
||||
console.log('something bad happened!')
|
||||
console.log(e)
|
||||
})
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
const server = program => {
|
||||
const Http = require('http')
|
||||
const Https = require('https')
|
||||
const FS = require('fs')
|
||||
const Express = require('express')
|
||||
const Crypto = require('crypto')
|
||||
const Dotenv = require('dotenv')
|
||||
const Storage = require('node-persist')
|
||||
const Path = require('path')
|
||||
const { Logger: CommonLogger } = require('shock-common')
|
||||
const binaryParser = require('socket.io-msgpack-parser')
|
||||
|
||||
const LightningServices = require('../utils/lightningServices')
|
||||
const app = Express()
|
||||
|
||||
const compression = require('compression')
|
||||
const bodyParser = require('body-parser')
|
||||
const session = require('express-session')
|
||||
const methodOverride = require('method-override')
|
||||
const qrcode = require('qrcode-terminal')
|
||||
const relayClient = require('hybrid-relay-client/build')
|
||||
const {
|
||||
sensitiveRoutes,
|
||||
nonEncryptedRoutes
|
||||
} = require('../utils/protectedRoutes')
|
||||
|
||||
/**
|
||||
* An offline-only private key used for authenticating a client's key
|
||||
* exchange. Neither the tunnel nor the WWW should see this private key, it
|
||||
* should only be served through STDOUT (via QR or else).
|
||||
*/
|
||||
const accessSecret = ECCrypto.generatePrivate()
|
||||
const accessSecretBase64 = accessSecret.toString('base64')
|
||||
|
||||
// load app default configuration data
|
||||
const defaults = require('../config/defaults')(program.mainnet)
|
||||
const rootFolder = program.rootPath || process.resourcesPath || __dirname
|
||||
|
||||
// define env variables
|
||||
Dotenv.config()
|
||||
|
||||
const serverPort = program.serverport || defaults.serverPort
|
||||
const serverHost = program.serverhost || defaults.serverHost
|
||||
const tunnelHost = process.env.LOCAL_TUNNEL_SERVER || defaults.localtunnelHost
|
||||
|
||||
// setup winston logging ==========
|
||||
const logger = require('../config/log')
|
||||
|
||||
CommonLogger.setLogger(logger)
|
||||
|
||||
// utilities functions =================
|
||||
require('../utils/server-utils')(module)
|
||||
|
||||
logger.info('Mainnet Mode:', !!program.mainnet)
|
||||
|
||||
if (process.env.SHOCK_ENCRYPTION_ECC === 'false') {
|
||||
logger.error('Encryption Mode: false')
|
||||
} else {
|
||||
logger.info('Encryption Mode: true')
|
||||
}
|
||||
|
||||
const stringifyData = data => {
|
||||
if (typeof data === 'object') {
|
||||
const stringifiedData = JSON.stringify(data)
|
||||
return stringifiedData
|
||||
}
|
||||
|
||||
if (data.toString) {
|
||||
return data.toString()
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
const hashData = data => {
|
||||
return Crypto.createHash('SHA256')
|
||||
.update(Buffer.from(stringifyData(data)))
|
||||
.digest('hex')
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Express.Request} req
|
||||
* @param {Express.Response} res
|
||||
* @param {(() => void)} next
|
||||
*/
|
||||
const modifyResponseBody = (req, res, next) => {
|
||||
const deviceId = req.headers['encryption-device-id']
|
||||
const oldSend = res.send
|
||||
|
||||
console.log({
|
||||
deviceId,
|
||||
encryptionDisabled: process.env.SHOCK_ENCRYPTION_ECC === 'false',
|
||||
unprotectedRoute: nonEncryptedRoutes.includes(req.path)
|
||||
})
|
||||
|
||||
if (
|
||||
nonEncryptedRoutes.includes(req.path) ||
|
||||
process.env.SHOCK_ENCRYPTION_ECC === 'false'
|
||||
) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
// @ts-expect-error
|
||||
res.send = (...args) => {
|
||||
if (args[0] && args[0].ciphertext && args[0].iv) {
|
||||
logger.warn('Response loop detected!')
|
||||
oldSend.apply(res, args)
|
||||
return
|
||||
}
|
||||
|
||||
if (typeof deviceId !== 'string' || !deviceId) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
const authorized = ECC.devicePublicKeys.has(deviceId)
|
||||
|
||||
// Using classic promises syntax to avoid
|
||||
// modifying res.send's return type
|
||||
if (authorized && process.env.SHOCK_ENCRYPTION_ECC !== 'false') {
|
||||
const devicePub = Buffer.from(ECC.devicePublicKeys.get(deviceId))
|
||||
|
||||
ECCrypto.encrypt(devicePub, Buffer.from(args[0], 'utf-8')).then(
|
||||
encryptedMessage => {
|
||||
args[0] = JSON.stringify(encryptedMessage)
|
||||
oldSend.apply(res, args)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
if (!authorized || process.env.SHOCK_ENCRYPTION_ECC === 'false') {
|
||||
if (!authorized) {
|
||||
logger.warn(
|
||||
`An unauthorized Device ID is contacting the API: ${deviceId}`
|
||||
)
|
||||
logger.warn(
|
||||
`Authorized Device IDs: ${[...ECC.devicePublicKeys.keys()].join(
|
||||
', '
|
||||
)}`
|
||||
)
|
||||
}
|
||||
args[0] = JSON.stringify(args[0])
|
||||
oldSend.apply(res, args)
|
||||
}
|
||||
}
|
||||
|
||||
next()
|
||||
}
|
||||
|
||||
const wait = seconds =>
|
||||
new Promise(resolve => {
|
||||
const timer = setTimeout(() => resolve(timer), seconds * 1000)
|
||||
})
|
||||
|
||||
// eslint-disable-next-line consistent-return
|
||||
const startServer = async () => {
|
||||
try {
|
||||
LightningServices.setDefaults(program)
|
||||
if (!LightningServices.isInitialized()) {
|
||||
await LightningServices.init()
|
||||
}
|
||||
|
||||
await /** @type {Promise<void>} */ (new Promise((resolve, reject) => {
|
||||
LightningServices.services.lightning.getInfo({}, (err, res) => {
|
||||
if (
|
||||
err &&
|
||||
!err.details.includes('wallet not created') &&
|
||||
!err.details.includes('wallet locked')
|
||||
) {
|
||||
reject(err)
|
||||
} else {
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
}))
|
||||
|
||||
app.use(compression())
|
||||
|
||||
app.use((req, res, next) => {
|
||||
if (process.env.ROUTE_LOGGING === 'true') {
|
||||
if (sensitiveRoutes[req.method][req.path]) {
|
||||
logger.info(
|
||||
JSON.stringify({
|
||||
time: new Date(),
|
||||
ip: req.ip,
|
||||
method: req.method,
|
||||
path: req.path,
|
||||
sessionId: req.sessionId
|
||||
})
|
||||
)
|
||||
} else {
|
||||
logger.info(
|
||||
JSON.stringify({
|
||||
time: new Date(),
|
||||
ip: req.ip,
|
||||
method: req.method,
|
||||
path: req.path,
|
||||
body: req.body,
|
||||
query: req.query,
|
||||
sessionId: req.sessionId
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
next()
|
||||
})
|
||||
|
||||
app.use((req, res, next) => {
|
||||
res.set('Version', program.version ? program.version() : 'N/A')
|
||||
next()
|
||||
})
|
||||
|
||||
const storageDirectory = Path.resolve(
|
||||
rootFolder,
|
||||
`${program.rootPath ? '.' : '..'}/.storage`
|
||||
)
|
||||
|
||||
await Storage.init({
|
||||
dir: storageDirectory
|
||||
}) /*
|
||||
if (false) {
|
||||
await Storage.removeItem('tunnel/token')
|
||||
await Storage.removeItem('tunnel/subdomain')
|
||||
await Storage.removeItem('tunnel/url')
|
||||
}*/
|
||||
|
||||
const storePersistentRandomField = async ({ fieldName, length = 16 }) => {
|
||||
const randomField = await Storage.getItem(fieldName)
|
||||
|
||||
if (randomField) {
|
||||
return randomField
|
||||
}
|
||||
|
||||
const newValue = await ECC.generateRandomString(length)
|
||||
await Storage.setItem(fieldName, newValue)
|
||||
return newValue
|
||||
}
|
||||
|
||||
const [sessionSecret] = await Promise.all([
|
||||
storePersistentRandomField({
|
||||
fieldName: 'config/sessionSecret'
|
||||
}),
|
||||
storePersistentRandomField({
|
||||
fieldName: 'encryption/hostId',
|
||||
length: 8
|
||||
})
|
||||
])
|
||||
|
||||
app.use(
|
||||
session({
|
||||
secret: sessionSecret,
|
||||
cookie: { maxAge: defaults.sessionMaxAge },
|
||||
resave: true,
|
||||
rolling: true,
|
||||
saveUninitialized: true
|
||||
})
|
||||
)
|
||||
app.use(bodyParser.urlencoded({ extended: true }))
|
||||
app.use(bodyParser.json({ limit: '500kb' }))
|
||||
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
|
||||
app.use(methodOverride())
|
||||
// WARNING
|
||||
// error handler middleware, KEEP 4 parameters as express detects the
|
||||
// arity of the function to treat it as a err handling middleware
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
app.use((err, _, res, __) => {
|
||||
// Do logging and user-friendly error message display
|
||||
logger.error(err)
|
||||
res.status(500).send({ status: 500, errorMessage: 'internal error' })
|
||||
})
|
||||
|
||||
const CA = program.httpsCert
|
||||
const CA_KEY = program.httpsCertKey
|
||||
|
||||
const createServer = () => {
|
||||
try {
|
||||
if (program.useTLS) {
|
||||
const key = FS.readFileSync(CA_KEY, 'utf-8')
|
||||
const cert = FS.readFileSync(CA, 'utf-8')
|
||||
|
||||
const httpsServer = Https.createServer({ key, cert }, app)
|
||||
|
||||
return httpsServer
|
||||
}
|
||||
|
||||
const httpServer = new Http.Server(app)
|
||||
return httpServer
|
||||
} catch (err) {
|
||||
logger.error(err.message)
|
||||
logger.error(
|
||||
'An error has occurred while finding an LND cert to use to open an HTTPS server'
|
||||
)
|
||||
logger.warn('Falling back to opening an HTTP server...')
|
||||
const httpServer = new Http.Server(app)
|
||||
return httpServer
|
||||
}
|
||||
}
|
||||
|
||||
const serverInstance = await createServer()
|
||||
|
||||
require('socket.io')(serverInstance, {
|
||||
parser: binaryParser,
|
||||
transports: ['websocket', 'polling'],
|
||||
cors: {
|
||||
origin: (origin, callback) => {
|
||||
callback(null, true)
|
||||
},
|
||||
allowedHeaders: [
|
||||
'Origin',
|
||||
'X-Requested-With',
|
||||
'Content-Type',
|
||||
'Accept',
|
||||
'Authorization',
|
||||
'public-key-for-decryption',
|
||||
'encryption-device-id'
|
||||
],
|
||||
credentials: true
|
||||
}
|
||||
})
|
||||
|
||||
require('./routes')(
|
||||
app,
|
||||
{
|
||||
...defaults,
|
||||
lndAddress: program.lndAddress,
|
||||
cliArgs: program
|
||||
},
|
||||
{
|
||||
serverPort,
|
||||
useTLS: program.useTLS,
|
||||
CA,
|
||||
CA_KEY,
|
||||
runPrivateKey,
|
||||
runPublicKey,
|
||||
accessSecret
|
||||
}
|
||||
)
|
||||
|
||||
// enable CORS headers
|
||||
app.use(require('./cors'))
|
||||
// app.use(bodyParser.json({limit: '100000mb'}));
|
||||
app.use(bodyParser.json({ limit: '50mb' }))
|
||||
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }))
|
||||
if (process.env.SHOCK_ENCRYPTION_ECC !== 'false') {
|
||||
app.use(modifyResponseBody)
|
||||
}
|
||||
|
||||
if (program.tunnel) {
|
||||
const [relayToken, relayId, relayUrl] = await Promise.all([
|
||||
Storage.getItem('relay/token'),
|
||||
Storage.getItem('relay/id'),
|
||||
Storage.getItem('relay/url')
|
||||
])
|
||||
const opts = {
|
||||
relayId,
|
||||
relayToken,
|
||||
address: tunnelHost,
|
||||
port: serverPort
|
||||
}
|
||||
logger.info(opts)
|
||||
relayClient.default(opts, async (connected, params) => {
|
||||
if (connected) {
|
||||
const noProtocolAddress = params.address.replace(
|
||||
/^http(?<secure>s)?:\/\//giu,
|
||||
''
|
||||
)
|
||||
await Promise.all([
|
||||
Storage.setItem('relay/token', params.relayToken),
|
||||
Storage.setItem('relay/id', params.relayId),
|
||||
Storage.setItem('relay/url', noProtocolAddress)
|
||||
])
|
||||
const dataToQr = JSON.stringify({
|
||||
URI: `https://${params.relayId}@${noProtocolAddress}`,
|
||||
// Null-check is just to please typescript
|
||||
accessSecret: accessSecretBase64
|
||||
})
|
||||
qrcode.generate(dataToQr, { small: false })
|
||||
logger.info(`connect to ${params.relayId}@${noProtocolAddress}:443`)
|
||||
console.log('\n')
|
||||
console.log(`Here's your access secret:`)
|
||||
console.log('\n')
|
||||
console.log(accessSecretBase64)
|
||||
console.log('\n')
|
||||
console.log('\n')
|
||||
} else {
|
||||
logger.error('!! Relay did not connect to server !!')
|
||||
}
|
||||
})
|
||||
} else {
|
||||
console.log('\n')
|
||||
console.log(`Here's your access secret:`)
|
||||
console.log('\n')
|
||||
console.log(accessSecretBase64)
|
||||
console.log('\n')
|
||||
console.log('\n')
|
||||
}
|
||||
|
||||
serverInstance.listen(serverPort, serverHost)
|
||||
logger.info('App listening on ' + serverHost + ' port ' + serverPort)
|
||||
// @ts-expect-error
|
||||
module.server = serverInstance
|
||||
} catch (err) {
|
||||
logger.error({ exception: err, message: err.message, code: err.code })
|
||||
logger.info('Restarting server in 30 seconds...')
|
||||
await wait(30)
|
||||
startServer()
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
startServer()
|
||||
}
|
||||
|
||||
module.exports = server
|
||||
34
src/services/lnd/addInvoiceReq.ts
Normal file
34
src/services/lnd/addInvoiceReq.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import { OpenChannelRequest, Invoice } from "../../../proto/lnd/lightning";
|
||||
|
||||
export const AddInvoiceReq = (value: number, memo = "", privateHints = false, expiry = 60 * 60): Invoice => ({
|
||||
expiry: BigInt(expiry),
|
||||
memo: memo,
|
||||
private: privateHints,
|
||||
value: BigInt(value),
|
||||
|
||||
fallbackAddr: "",
|
||||
cltvExpiry: 0n,
|
||||
descriptionHash: Buffer.alloc(0),
|
||||
features: {},
|
||||
isAmp: false,
|
||||
rPreimage: Buffer.alloc(0),
|
||||
routeHints: [],
|
||||
valueMsat: 0n,
|
||||
|
||||
addIndex: 0n,
|
||||
ampInvoiceState: {},
|
||||
amtPaidMsat: 0n,
|
||||
amtPaidSat: 0n,
|
||||
creationDate: 0n,
|
||||
htlcs: [],
|
||||
isKeysend: false,
|
||||
paymentAddr: Buffer.alloc(0),
|
||||
paymentRequest: "",
|
||||
rHash: Buffer.alloc(0),
|
||||
settleDate: 0n,
|
||||
settleIndex: 0n,
|
||||
state: 0,
|
||||
|
||||
amtPaid: 0n,
|
||||
settled: false,
|
||||
})
|
||||
36
src/services/lnd/index.spec.ts
Normal file
36
src/services/lnd/index.spec.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import 'dotenv/config' // TODO - test env
|
||||
import { AfterAll, BeforeAll, expect, FTest, FTestSuite, Test, TestSuite } from 'testyts';
|
||||
import LndHandler, { LoadLndSettingsFromEnv } from '.'
|
||||
import * as Types from '../../../proto/autogenerated/ts/types';
|
||||
@TestSuite()
|
||||
export class LndTestSuite {
|
||||
lnd: LndHandler
|
||||
@BeforeAll()
|
||||
createLnd() {
|
||||
this.lnd = new LndHandler(LoadLndSettingsFromEnv())
|
||||
}
|
||||
@AfterAll()
|
||||
stopStreams() {
|
||||
}
|
||||
@Test()
|
||||
async getAlias() {
|
||||
const res = await this.lnd.GetInfo()
|
||||
expect.toBeEqual(res.alias, "alice")
|
||||
}
|
||||
@Test()
|
||||
async newAddress() {
|
||||
const res = await this.lnd.NewAddress(Types.AddressType.WITNESS_PUBKEY_HASH)
|
||||
console.log(res)
|
||||
}
|
||||
@Test()
|
||||
async newInvoice() {
|
||||
const res = await this.lnd.NewInvoice(1000)
|
||||
console.log(res)
|
||||
}
|
||||
|
||||
@Test()
|
||||
async openChannel() {
|
||||
//const res = await this.lnd.OpenChannel("025ed7fc85fc05a07fc5acc13a6e3836cd11c5587c1d400afcd22630a9e230eb7a", "", 20000, 0)
|
||||
}
|
||||
|
||||
}
|
||||
221
src/services/lnd/index.ts
Normal file
221
src/services/lnd/index.ts
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
//const grpc = require('@grpc/grpc-js');
|
||||
import { credentials, Metadata } from '@grpc/grpc-js'
|
||||
import { GrpcTransport } from "@protobuf-ts/grpc-transport";
|
||||
import fs from 'fs'
|
||||
import * as Types from '../../../proto/autogenerated/ts/types'
|
||||
import { LightningClient } from '../../../proto/lnd/lightning.client'
|
||||
import { InvoicesClient } from '../../../proto/lnd/invoices.client'
|
||||
import { RouterClient } from '../../../proto/lnd/router.client'
|
||||
import { GetInfoResponse, AddressType, NewAddressResponse, AddInvoiceResponse, Invoice_InvoiceState, PayReq, Payment_PaymentStatus, Payment } from '../../../proto/lnd/lightning'
|
||||
import { OpenChannelReq } from './openChannelReq';
|
||||
import { AddInvoiceReq } from './addInvoiceReq';
|
||||
import { PayInvoiceReq } from './payInvoiceReq';
|
||||
const DeadLineMetadata = (deadline = 10 * 1000) => ({ deadline: Date.now() + deadline })
|
||||
export type LndSettings = {
|
||||
lndAddr: string
|
||||
lndCertPath: string
|
||||
lndMacaroonPath: string
|
||||
walletAccount: string
|
||||
feeRateLimit: number
|
||||
feeFixedLimit: number
|
||||
}
|
||||
export const LoadLndSettingsFromEnv = (test = false): LndSettings => {
|
||||
const lndAddr = process.env.LND_ADDRESS;
|
||||
const lndCertPath = process.env.LND_CERT_PATH;
|
||||
const lndMacaroonPath = process.env.LND_MACAROON_PATH;
|
||||
if (!lndAddr) throw new Error(`missing env for LND_ADDRESS`)
|
||||
if (!lndCertPath) throw new Error(`missing env for LND_CERT_PATH`)
|
||||
if (!lndMacaroonPath) throw new Error(`missing env for LND_MACAROON_PATH`)
|
||||
|
||||
if (!process.env.LIMIT_FEE_RATE_MILLISATS) {
|
||||
throw new Error(`missing env for LIMIT_FEE_RATE_MILLISATS`)
|
||||
}
|
||||
if (isNaN(+process.env.LIMIT_FEE_RATE_MILLISATS) || !Number.isInteger(+process.env.LIMIT_FEE_RATE_MILLISATS)) {
|
||||
throw new Error("LIMIT_FEE_RATE_MILLISATS must be an integer number");
|
||||
}
|
||||
|
||||
if (!process.env.LIMIT_FEE_FIXED_SATS) {
|
||||
throw new Error(`missing env for LIMIT_FEE_FIXED_SATS`)
|
||||
}
|
||||
if (isNaN(+process.env.LIMIT_FEE_FIXED_SATS) || !Number.isInteger(+process.env.LIMIT_FEE_FIXED_SATS)) {
|
||||
throw new Error("LIMIT_FEE_FIXED_SATS must be an integer number");
|
||||
}
|
||||
const feeRateLimit = +process.env.LIMIT_FEE_RATE_MILLISATS / 1000
|
||||
const feeFixedLimit = +process.env.LIMIT_FEE_FIXED_SATS
|
||||
|
||||
const walletAccount = process.env.LND_WALLET_ACCOUNT || ""
|
||||
return { lndAddr, lndCertPath, lndMacaroonPath, walletAccount, feeRateLimit, feeFixedLimit }
|
||||
}
|
||||
type TxOutput = {
|
||||
hash: string
|
||||
index: number
|
||||
}
|
||||
export type AddressPaidCb = (txOutput: TxOutput, address: string, amount: number) => void
|
||||
export type InvoicePaidCb = (paymentRequest: string, amount: number) => void
|
||||
export default class {
|
||||
lightning: LightningClient
|
||||
invoices: InvoicesClient
|
||||
router: RouterClient
|
||||
settings: LndSettings
|
||||
ready = false
|
||||
latestKnownBlockHeigh = 0
|
||||
latestKnownSettleIndex = 0
|
||||
abortController = new AbortController()
|
||||
addressPaidCb: AddressPaidCb
|
||||
invoicePaidCb: InvoicePaidCb
|
||||
constructor(settings: LndSettings, addressPaidCb: AddressPaidCb, invoicePaidCb: InvoicePaidCb) {
|
||||
this.settings = settings
|
||||
this.addressPaidCb = addressPaidCb
|
||||
this.invoicePaidCb = invoicePaidCb
|
||||
const { lndAddr, lndCertPath, lndMacaroonPath } = this.settings
|
||||
const lndCert = fs.readFileSync(lndCertPath);
|
||||
const macaroon = fs.readFileSync(lndMacaroonPath).toString('hex');
|
||||
const sslCreds = credentials.createSsl(lndCert);
|
||||
const macaroonCreds = credentials.createFromMetadataGenerator(
|
||||
function (args: any, callback: any) {
|
||||
let metadata = new Metadata();
|
||||
metadata.add('macaroon', macaroon);
|
||||
callback(null, metadata);
|
||||
},
|
||||
);
|
||||
const creds = credentials.combineChannelCredentials(
|
||||
sslCreds,
|
||||
macaroonCreds,
|
||||
);
|
||||
const transport = new GrpcTransport({ host: lndAddr, channelCredentials: creds })
|
||||
this.lightning = new LightningClient(transport)
|
||||
this.invoices = new InvoicesClient(transport)
|
||||
this.router = new RouterClient(transport)
|
||||
this.SubscribeAddressPaid()
|
||||
}
|
||||
Stop() {
|
||||
this.abortController.abort()
|
||||
}
|
||||
async Warmup() { this.ready = true }
|
||||
|
||||
async GetInfo(): Promise<GetInfoResponse> {
|
||||
const res = await this.lightning.getInfo({}, DeadLineMetadata())
|
||||
return res.response
|
||||
}
|
||||
checkReady() {
|
||||
if (!this.ready) throw new Error("lnd not ready, warmup required before usage")
|
||||
}
|
||||
SubscribeAddressPaid() {
|
||||
const stream = this.lightning.subscribeTransactions({
|
||||
account: this.settings.walletAccount,
|
||||
endHeight: 0,
|
||||
startHeight: this.latestKnownBlockHeigh,
|
||||
}, { abort: this.abortController.signal })
|
||||
stream.responses.onMessage(tx => {
|
||||
if (tx.blockHeight > this.latestKnownBlockHeigh) {
|
||||
this.latestKnownBlockHeigh = tx.blockHeight
|
||||
}
|
||||
if (tx.numConfirmations > 0) {
|
||||
tx.outputDetails.forEach(output => {
|
||||
if (output.isOurAddress) {
|
||||
this.addressPaidCb({ hash: tx.txHash, index: Number(output.outputIndex) }, output.address, Number(output.amount))
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
stream.responses.onError(error => {
|
||||
// TODO...
|
||||
})
|
||||
}
|
||||
|
||||
SubscribeInvoicePaid() {
|
||||
const stream = this.lightning.subscribeInvoices({
|
||||
settleIndex: BigInt(this.latestKnownSettleIndex),
|
||||
addIndex: 0n,
|
||||
}, { abort: this.abortController.signal })
|
||||
stream.responses.onMessage(invoice => {
|
||||
if (invoice.state === Invoice_InvoiceState.SETTLED) {
|
||||
this.latestKnownSettleIndex = Number(invoice.settleIndex)
|
||||
this.invoicePaidCb(invoice.paymentRequest, Number(invoice.amtPaidSat))
|
||||
}
|
||||
})
|
||||
stream.responses.onError(error => {
|
||||
// TODO...
|
||||
})
|
||||
}
|
||||
async NewAddress(addressType: Types.AddressType): Promise<NewAddressResponse> {
|
||||
this.checkReady()
|
||||
let lndAddressType: AddressType
|
||||
switch (addressType) {
|
||||
case Types.AddressType.NESTED_PUBKEY_HASH:
|
||||
lndAddressType = AddressType.NESTED_PUBKEY_HASH
|
||||
break;
|
||||
case Types.AddressType.WITNESS_PUBKEY_HASH:
|
||||
lndAddressType = AddressType.WITNESS_PUBKEY_HASH
|
||||
break;
|
||||
case Types.AddressType.TAPROOT_PUBKEY:
|
||||
lndAddressType = AddressType.TAPROOT_PUBKEY
|
||||
break;
|
||||
default:
|
||||
throw new Error("unknown address type " + addressType)
|
||||
}
|
||||
const res = await this.lightning.newAddress({ account: this.settings.walletAccount, type: lndAddressType }, DeadLineMetadata())
|
||||
return res.response
|
||||
}
|
||||
|
||||
async NewInvoice(value: number): Promise<AddInvoiceResponse> {
|
||||
this.checkReady()
|
||||
const res = await this.lightning.addInvoice(AddInvoiceReq(value), DeadLineMetadata())
|
||||
return res.response
|
||||
}
|
||||
|
||||
async DecodeInvoice(paymentRequest: string): Promise<PayReq> {
|
||||
const res = await this.lightning.decodePayReq({ payReq: paymentRequest }, DeadLineMetadata())
|
||||
return res.response
|
||||
}
|
||||
|
||||
GetFeeLimitAmount(amount: number) {
|
||||
return Math.ceil(amount * this.settings.feeRateLimit + this.settings.feeFixedLimit);
|
||||
}
|
||||
|
||||
async PayInvoice(invoice: string, amount: number, feeLimit: number): Promise<Payment> {
|
||||
this.checkReady()
|
||||
const abortController = new AbortController()
|
||||
const stream = this.router.sendPaymentV2(PayInvoiceReq(invoice, amount, feeLimit), { abort: abortController.signal })
|
||||
return new Promise((res, rej) => {
|
||||
stream.responses.onError(error => {
|
||||
rej(error)
|
||||
})
|
||||
stream.responses.onMessage(payment => {
|
||||
switch (payment.status) {
|
||||
case Payment_PaymentStatus.FAILED:
|
||||
rej(payment.failureReason)
|
||||
return
|
||||
case Payment_PaymentStatus.SUCCEEDED:
|
||||
res(payment)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
async OpenChannel(destination: string, closeAddress: string, fundingAmount: number, pushSats: number): Promise<string> {
|
||||
this.checkReady()
|
||||
const abortController = new AbortController()
|
||||
const req = OpenChannelReq(destination, closeAddress, fundingAmount, pushSats)
|
||||
const stream = this.lightning.openChannel(req, { abort: abortController.signal })
|
||||
return new Promise((res, rej) => {
|
||||
stream.responses.onMessage(message => {
|
||||
switch (message.update.oneofKind) {
|
||||
case 'chanPending':
|
||||
abortController.abort()
|
||||
res(Buffer.from(message.pendingChanId).toString('base64'))
|
||||
break
|
||||
default:
|
||||
abortController.abort()
|
||||
rej("unexpected state response: " + message.update.oneofKind)
|
||||
}
|
||||
})
|
||||
stream.responses.onError(error => {
|
||||
rej(error)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
32
src/services/lnd/openChannelReq.ts
Normal file
32
src/services/lnd/openChannelReq.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { OpenChannelRequest } from "../../../proto/lnd/lightning";
|
||||
|
||||
export const OpenChannelReq = (destination: string, closeAddress: string, fundingAmount: number, pushSats: number): OpenChannelRequest => ({
|
||||
nodePubkey: Buffer.from(destination, 'hex'),
|
||||
closeAddress: closeAddress,
|
||||
localFundingAmount: BigInt(fundingAmount),
|
||||
pushSat: BigInt(pushSats),
|
||||
|
||||
satPerVbyte: 0n, // TBD
|
||||
private: false,
|
||||
minConfs: 0, // TBD
|
||||
baseFee: 0n, // TBD
|
||||
feeRate: 0n, // TBD
|
||||
zeroConf: false,
|
||||
maxLocalCsv: 0,
|
||||
remoteCsvDelay: 0,
|
||||
spendUnconfirmed: false,
|
||||
minHtlcMsat: 0n,
|
||||
remoteChanReserveSat: 0n,
|
||||
remoteMaxHtlcs: 0,
|
||||
remoteMaxValueInFlightMsat: 0n,
|
||||
targetConf: 0,
|
||||
useBaseFee: false,
|
||||
useFeeRate: false,
|
||||
|
||||
// Default stuff
|
||||
commitmentType: 0,
|
||||
scidAlias: false,
|
||||
nodePubkeyString: "",
|
||||
satPerByte: 0n,
|
||||
|
||||
})
|
||||
30
src/services/lnd/payInvoiceReq.ts
Normal file
30
src/services/lnd/payInvoiceReq.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { OpenChannelRequest } from "../../../proto/lnd/lightning";
|
||||
import { SendPaymentRequest } from "../../../proto/lnd/router";
|
||||
|
||||
export const PayInvoiceReq = (invoice: string, amount: number, feeLimit: number): SendPaymentRequest => ({
|
||||
amt: BigInt(amount),
|
||||
feeLimitSat: BigInt(feeLimit),
|
||||
noInflightUpdates: true,
|
||||
paymentRequest: invoice,
|
||||
maxParts: 3,
|
||||
timeoutSeconds: 50,
|
||||
|
||||
allowSelfPayment: false,
|
||||
amp: false,
|
||||
amtMsat: 0n,
|
||||
cltvLimit: 0,
|
||||
dest: Buffer.alloc(0),
|
||||
destCustomRecords: {},
|
||||
destFeatures: [],
|
||||
feeLimitMsat: 0n,
|
||||
finalCltvDelta: 0,
|
||||
lastHopPubkey: Buffer.alloc(0),
|
||||
maxShardSizeMsat: 0n,
|
||||
outgoingChanIds: [],
|
||||
paymentAddr: Buffer.alloc(0),
|
||||
paymentHash: Buffer.alloc(0),
|
||||
routeHints: [],
|
||||
timePref: 0,
|
||||
|
||||
outgoingChanId: ""
|
||||
})
|
||||
97
src/services/main/index.ts
Normal file
97
src/services/main/index.ts
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
import jwt from 'jsonwebtoken'
|
||||
import Storage, { LoadStorageSettingsFromEnv, StorageSettings } from '../storage'
|
||||
import * as Types from '../../../proto/autogenerated/ts/types'
|
||||
import LND, { AddressPaidCb, InvoicePaidCb, LndSettings, LoadLndSettingsFromEnv } from '../lnd'
|
||||
export type MainSettings = {
|
||||
storageSettings: StorageSettings,
|
||||
lndSettings: LndSettings,
|
||||
jwtSecret: string
|
||||
}
|
||||
export const LoadMainSettingsFromEnv = (test = false): MainSettings => {
|
||||
const jwtSecret = process.env.JWT_SECRET;
|
||||
if (!jwtSecret) throw new Error(`missing env for JWT_SECRET`)
|
||||
return {
|
||||
lndSettings: LoadLndSettingsFromEnv(test),
|
||||
storageSettings: LoadStorageSettingsFromEnv(test),
|
||||
jwtSecret
|
||||
}
|
||||
}
|
||||
export default class {
|
||||
storage: Storage
|
||||
lnd: LND
|
||||
settings: MainSettings
|
||||
constructor(settings: MainSettings) {
|
||||
this.settings = settings
|
||||
this.storage = new Storage(settings.storageSettings)
|
||||
this.lnd = new LND(settings.lndSettings, this.addressPaidCb, this.invoicePaidCb)
|
||||
}
|
||||
addressPaidCb: AddressPaidCb = (txOutput, address, amount) => {
|
||||
this.storage.StartTransaction(async tx => {
|
||||
const userAddress = await this.storage.GetAddressOwner(address, tx)
|
||||
if (!userAddress) { return }
|
||||
// This call will fail if the transaction is already registered
|
||||
const addedTx = await this.storage.AddAddressTransaction(address, txOutput.hash, txOutput.index, amount)
|
||||
await this.storage.IncrementUserBalance(userAddress.user.user_id, addedTx.amount, tx)
|
||||
})
|
||||
}
|
||||
invoicePaidCb: InvoicePaidCb = (paymentRequest, amount) => {
|
||||
this.storage.StartTransaction(async tx => {
|
||||
const userInvoice = await this.storage.GetInvoiceOwner(paymentRequest, tx)
|
||||
if (!userInvoice || userInvoice.paid) { return }
|
||||
// This call will fail if the invoice is already registered
|
||||
await this.storage.FlagInvoiceAsPaid(userInvoice.serial_id, amount, tx)
|
||||
await this.storage.IncrementUserBalance(userInvoice.user.user_id, amount)
|
||||
})
|
||||
}
|
||||
SignUserToken(userId: string): string {
|
||||
return jwt.sign({ userId }, this.settings.jwtSecret);
|
||||
}
|
||||
|
||||
DecodeUserToken(token?: string): string {
|
||||
if (!token) throw new Error("empty auth token provided")
|
||||
return (jwt.verify(token, this.settings.jwtSecret) as { userId: string }).userId
|
||||
}
|
||||
|
||||
async AddUser(req: Types.AddUserRequest): Promise<Types.AddUserResponse> {
|
||||
const newUser = await this.storage.AddUser(req.name, req.callback_url, req.secret)
|
||||
return {
|
||||
user_id: newUser.user_id,
|
||||
auth_token: this.SignUserToken(newUser.user_id)
|
||||
}
|
||||
}
|
||||
|
||||
async NewAddress(userId: string, req: Types.NewAddressRequest): Promise<Types.NewAddressResponse> {
|
||||
const res = await this.lnd.NewAddress(req.address_type)
|
||||
const userAddress = await this.storage.AddUserAddress(userId, res.address)
|
||||
return {
|
||||
address: userAddress.address
|
||||
}
|
||||
}
|
||||
|
||||
async NewInvoice(userId: string, req: Types.NewInvoiceRequest): Promise<Types.NewInvoiceResponse> {
|
||||
const res = await this.lnd.NewInvoice(req.amount_sats)
|
||||
const userInvoice = await this.storage.AddUserInvoice(userId, res.paymentRequest)
|
||||
return {
|
||||
invoice: userInvoice.invoice
|
||||
}
|
||||
}
|
||||
|
||||
async PayInvoice(userId: string, req: Types.PayInvoiceRequest): Promise<Types.PayInvoiceResponse> {
|
||||
const decoded = await this.lnd.DecodeInvoice(req.invoice)
|
||||
const payAmount = Number(decoded.numSatoshis)
|
||||
const feeLimit = this.lnd.GetFeeLimitAmount(payAmount)
|
||||
const decrement = payAmount + feeLimit
|
||||
// this call will fail if the user balance is not enough
|
||||
await this.storage.DecrementUserBalance(userId, decrement)
|
||||
try {
|
||||
await this.lnd.PayInvoice(req.invoice, req.amount, feeLimit)
|
||||
|
||||
} catch (e) {
|
||||
await this.storage.IncrementUserBalance(userId, decrement)
|
||||
throw e
|
||||
}
|
||||
await this.storage.AddUserPayment(userId, req.invoice,)
|
||||
}
|
||||
|
||||
async OpenChannel(userId: string, req: Types.OpenChannelRequest): Promise<Types.OpenChannelResponse> { throw new Error("WIP") }
|
||||
}
|
||||
48
src/services/serverMethods/index.ts
Normal file
48
src/services/serverMethods/index.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import * as Types from '../../../proto/autogenerated/ts/types'
|
||||
import Main from '../main'
|
||||
export default (mainHandler: Main): Types.ServerMethods => {
|
||||
return {
|
||||
EncryptionExchange: async (ctx: Types.EncryptionExchange_Context, req: Types.EncryptionExchangeRequest): Promise<void> => { },
|
||||
Health: async (ctx: Types.Health_Context): Promise<void> => { },
|
||||
LndGetInfo: async (ctx: Types.LndGetInfo_Context): Promise<Types.LndGetInfoResponse> => {
|
||||
const info = await mainHandler.lnd.GetInfo()
|
||||
return { alias: info.alias }
|
||||
},
|
||||
AddUser: async (ctx: Types.GuestContext, req: Types.AddUserRequest): Promise<Types.AddUserResponse> => {
|
||||
const err = Types.AddUserRequestValidate(req, {
|
||||
callback_url_CustomCheck: url => url.startsWith("http://") || url.startsWith("https://"),
|
||||
name_CustomCheck: name => name.length > 0,
|
||||
secret_CustomCheck: secret => secret.length >= 8
|
||||
})
|
||||
if (err != null) throw new Error(err.message)
|
||||
return mainHandler.AddUser(req)
|
||||
},
|
||||
AuthUser: async (ctx: Types.GuestContext, req: Types.AuthUserRequest): Promise<Types.AuthUserResponse> => {
|
||||
throw new Error("unimplemented")
|
||||
},
|
||||
OpenChannel: async (ctx: Types.UserContext, req: Types.OpenChannelRequest): Promise<Types.OpenChannelResponse> => {
|
||||
const err = Types.OpenChannelRequestValidate(req, {
|
||||
funding_amount_CustomCheck: amt => amt > 0,
|
||||
push_amount_CustomCheck: amt => amt > 0,
|
||||
destination_CustomCheck: dest => dest !== ""
|
||||
})
|
||||
if (err != null) throw new Error(err.message)
|
||||
return mainHandler.OpenChannel(ctx.user_id, req)
|
||||
},
|
||||
NewAddress: async (ctx: Types.UserContext, req: Types.NewAddressRequest): Promise<Types.NewAddressResponse> => {
|
||||
return mainHandler.NewAddress(ctx.user_id, req)
|
||||
},
|
||||
PayAddress: async (ctx: Types.UserContext, req: Types.PayAddressRequest): Promise<Types.PayAddressResponse> => {
|
||||
throw new Error("unimplemented")
|
||||
},
|
||||
NewInvoice: async (ctx: Types.UserContext, req: Types.NewInvoiceRequest): Promise<Types.NewInvoiceResponse> => {
|
||||
throw new Error("unimplemented")
|
||||
},
|
||||
PayInvoice: async (ctx: Types.UserContext, req: Types.PayInvoiceRequest): Promise<Types.PayInvoiceResponse> => {
|
||||
throw new Error("unimplemented")
|
||||
},
|
||||
GetOpenChannelLNURL: async (ctx: Types.UserContext): Promise<Types.GetOpenChannelLNURLResponse> => {
|
||||
throw new Error("unimplemented")
|
||||
}
|
||||
}
|
||||
}
|
||||
24
src/services/storage/db.ts
Normal file
24
src/services/storage/db.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import "reflect-metadata"
|
||||
import { DataSource } from "typeorm"
|
||||
import { AddressTransaction } from "./entity/AddressTransaction"
|
||||
import { User } from "./entity/User"
|
||||
import { UserAddress } from "./entity/UserAddress"
|
||||
import { UserInvoice } from "./entity/UserInvoice"
|
||||
import { UserPayment } from "./entity/UserPayment"
|
||||
export type DbSettings = {
|
||||
databaseFile: string
|
||||
}
|
||||
export const LoadDbSettingsFromEnv = (test = false): DbSettings => {
|
||||
const databaseFile = process.env.DATABASE_FILE
|
||||
if (!databaseFile) throw new Error(`missing env for DATABASE_FILE`)
|
||||
return { databaseFile: test ? ":memory:" : databaseFile }
|
||||
}
|
||||
export default async (settings: DbSettings) => {
|
||||
return new DataSource({
|
||||
type: "sqlite",
|
||||
database: settings.databaseFile,
|
||||
//logging: true,
|
||||
entities: [User, UserInvoice, UserAddress, AddressTransaction, UserPayment],
|
||||
synchronize: true
|
||||
}).initialize()
|
||||
}
|
||||
23
src/services/storage/entity/AddressTransaction.ts
Normal file
23
src/services/storage/entity/AddressTransaction.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import { Entity, PrimaryGeneratedColumn, Column, Index, Check, ManyToOne } from "typeorm"
|
||||
import { User } from "./User"
|
||||
import { UserAddress } from "./UserAddress"
|
||||
|
||||
@Entity()
|
||||
@Index("address_transaction_unique", ["tx_hash", "output_index"], { unique: true })
|
||||
export class AddressTransaction {
|
||||
|
||||
@PrimaryGeneratedColumn()
|
||||
serial_id: number
|
||||
|
||||
@ManyToOne(type => UserAddress)
|
||||
user_address: UserAddress
|
||||
|
||||
@Column()
|
||||
tx_hash: string
|
||||
|
||||
@Column()
|
||||
output_index: number
|
||||
|
||||
@Column()
|
||||
amount: number
|
||||
}
|
||||
29
src/services/storage/entity/User.ts
Normal file
29
src/services/storage/entity/User.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import { Entity, PrimaryGeneratedColumn, Column, Index, Check } from "typeorm"
|
||||
|
||||
@Entity()
|
||||
@Check(`"balance_sats" >= 0`)
|
||||
export class User {
|
||||
|
||||
@PrimaryGeneratedColumn()
|
||||
serial_id: number
|
||||
|
||||
@Column()
|
||||
@Index({ unique: true })
|
||||
user_id: string
|
||||
|
||||
@Column()
|
||||
@Index({ unique: true })
|
||||
name: string
|
||||
|
||||
@Column()
|
||||
secret_sha256: string
|
||||
|
||||
@Column()
|
||||
callbackUrl: string
|
||||
|
||||
@Column({ type: 'integer', default: 0 })
|
||||
balance_sats: number
|
||||
|
||||
@Column({ default: false })
|
||||
locked: boolean
|
||||
}
|
||||
19
src/services/storage/entity/UserAddress.ts
Normal file
19
src/services/storage/entity/UserAddress.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import { Entity, PrimaryGeneratedColumn, Column, Index, Check, ManyToOne } from "typeorm"
|
||||
import { User } from "./User"
|
||||
|
||||
@Entity()
|
||||
export class UserAddress {
|
||||
|
||||
@PrimaryGeneratedColumn()
|
||||
serial_id: number
|
||||
|
||||
@ManyToOne(type => User)
|
||||
user: User
|
||||
|
||||
@Column()
|
||||
@Index({ unique: true })
|
||||
address: string
|
||||
|
||||
@Column()
|
||||
callbackUrl: string
|
||||
}
|
||||
25
src/services/storage/entity/UserInvoice.ts
Normal file
25
src/services/storage/entity/UserInvoice.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { Entity, PrimaryGeneratedColumn, Column, Index, Check, ManyToOne } from "typeorm"
|
||||
import { User } from "./User"
|
||||
|
||||
@Entity()
|
||||
export class UserInvoice {
|
||||
|
||||
@PrimaryGeneratedColumn()
|
||||
serial_id: number
|
||||
|
||||
@ManyToOne(type => User)
|
||||
user: User
|
||||
|
||||
@Column()
|
||||
@Index({ unique: true })
|
||||
invoice: string
|
||||
|
||||
@Column({ default: false })
|
||||
paid: boolean
|
||||
|
||||
@Column()
|
||||
callbackUrl: string
|
||||
|
||||
@Column({ default: 0 })
|
||||
settle_amount: number
|
||||
}
|
||||
19
src/services/storage/entity/UserPayment.ts
Normal file
19
src/services/storage/entity/UserPayment.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import { Entity, PrimaryGeneratedColumn, Column, Index, Check, ManyToOne } from "typeorm"
|
||||
import { User } from "./User"
|
||||
|
||||
@Entity()
|
||||
export class UserPayment {
|
||||
|
||||
@PrimaryGeneratedColumn()
|
||||
serial_id: number
|
||||
|
||||
@ManyToOne(type => User)
|
||||
user: User
|
||||
|
||||
@Column()
|
||||
@Index({ unique: true })
|
||||
invoice: string
|
||||
|
||||
@Column()
|
||||
amount: number
|
||||
}
|
||||
135
src/services/storage/index.ts
Normal file
135
src/services/storage/index.ts
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
import { DataSource, EntityManager } from "typeorm"
|
||||
import crypto from 'crypto';
|
||||
import NewDB, { DbSettings, LoadDbSettingsFromEnv } from "./db"
|
||||
import { User } from "./entity/User"
|
||||
import { UserAddress } from "./entity/UserAddress";
|
||||
import { UserInvoice } from "./entity/UserInvoice";
|
||||
import { AddressTransaction } from "./entity/AddressTransaction";
|
||||
import { UserPayment } from "./entity/UserPayment";
|
||||
export type StorageSettings = {
|
||||
dbSettings: DbSettings
|
||||
}
|
||||
export const LoadStorageSettingsFromEnv = (test = false): StorageSettings => {
|
||||
return { dbSettings: LoadDbSettingsFromEnv(test) }
|
||||
}
|
||||
|
||||
export default class {
|
||||
DB: DataSource | EntityManager
|
||||
settings: StorageSettings
|
||||
constructor(settings: StorageSettings) {
|
||||
this.settings = settings
|
||||
}
|
||||
async Connect() {
|
||||
this.DB = await NewDB(this.settings.dbSettings)
|
||||
}
|
||||
StartTransaction(exec: (entityManager: EntityManager) => Promise<void>) {
|
||||
this.DB.transaction(exec)
|
||||
}
|
||||
async AddUser(name: string, callbackUrl: string, secret: string, entityManager = this.DB): Promise<User> {
|
||||
const newUser = entityManager.getRepository(User).create({
|
||||
user_id: crypto.randomBytes(32).toString('hex'),
|
||||
name: name,
|
||||
callbackUrl: callbackUrl,
|
||||
secret_sha256: crypto.createHash('sha256').update(secret).digest('base64')
|
||||
})
|
||||
return entityManager.getRepository(User).save(newUser)
|
||||
}
|
||||
FindUser(userId: string, entityManager = this.DB) {
|
||||
return entityManager.getRepository(User).findOne({
|
||||
where: {
|
||||
user_id: userId
|
||||
}
|
||||
})
|
||||
}
|
||||
async GetUser(userId: string, entityManager = this.DB): Promise<User> {
|
||||
const user = await this.FindUser(userId, entityManager)
|
||||
if (!user) {
|
||||
throw new Error(`user ${userId} not found`) // TODO: fix logs doxing
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
async AddAddressTransaction(address: string, txHash: string, outputIndex: number, amount: number, entityManager = this.DB) {
|
||||
const newAddressTransaction = entityManager.getRepository(AddressTransaction).create({
|
||||
user_address: { address: address },
|
||||
tx_hash: txHash,
|
||||
output_index: outputIndex,
|
||||
amount: amount
|
||||
})
|
||||
return entityManager.getRepository(AddressTransaction).save(newAddressTransaction)
|
||||
}
|
||||
|
||||
async AddUserAddress(userId: string, address: string, callbackUrl = "", entityManager = this.DB): Promise<UserAddress> {
|
||||
const newUserAddress = entityManager.getRepository(UserAddress).create({
|
||||
address,
|
||||
callbackUrl,
|
||||
user: { user_id: userId }
|
||||
})
|
||||
return entityManager.getRepository(UserAddress).save(newUserAddress)
|
||||
}
|
||||
|
||||
async FlagInvoiceAsPaid(invoiceSerialId: number, amount: number, entityManager = this.DB) {
|
||||
return entityManager.getRepository(UserInvoice).update(invoiceSerialId, { paid: true, settle_amount: amount })
|
||||
}
|
||||
|
||||
async AddUserInvoice(userId: string, invoice: string, callbackUrl = "", entityManager = this.DB): Promise<UserInvoice> {
|
||||
const newUserInvoice = entityManager.getRepository(UserInvoice).create({
|
||||
invoice: invoice,
|
||||
callbackUrl,
|
||||
user: { user_id: userId }
|
||||
})
|
||||
return entityManager.getRepository(UserInvoice).save(newUserInvoice)
|
||||
}
|
||||
|
||||
async GetAddressOwner(address: string, entityManager = this.DB): Promise<UserAddress | null> {
|
||||
return entityManager.getRepository(UserAddress).findOne({
|
||||
where: {
|
||||
address
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async GetInvoiceOwner(paymentRequest: string, entityManager = this.DB): Promise<UserInvoice | null> {
|
||||
return entityManager.getRepository(UserInvoice).findOne({
|
||||
where: {
|
||||
invoice: paymentRequest
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async AddUserPayment(userId: string, invoice: string, amount: number, entityManager = this.DB): Promise<UserPayment> {
|
||||
const newPayment = entityManager.getRepository(UserPayment).create({
|
||||
user: { user_id: userId },
|
||||
amount,
|
||||
invoice
|
||||
})
|
||||
return entityManager.getRepository(UserPayment).save(newPayment)
|
||||
}
|
||||
|
||||
LockUser(userId: string, entityManager = this.DB) {
|
||||
return entityManager.getRepository(User).update({
|
||||
user_id: userId
|
||||
}, { locked: true })
|
||||
}
|
||||
UnlockUser(userId: string, entityManager = this.DB) {
|
||||
return entityManager.getRepository(User).update({
|
||||
user_id: userId
|
||||
}, { locked: false })
|
||||
}
|
||||
async IncrementUserBalance(userId: string, increment: number, entityManager = this.DB) {
|
||||
const res = await entityManager.getRepository(User).increment({
|
||||
user_id: userId,
|
||||
}, "balance_sats", increment)
|
||||
if (!res.affected) {
|
||||
throw new Error("unaffected balance increment for " + userId) // TODO: fix logs doxing
|
||||
}
|
||||
}
|
||||
async DecrementUserBalance(userId: string, decrement: number, entityManager = this.DB) {
|
||||
const res = await entityManager.getRepository(User).decrement({
|
||||
user_id: userId,
|
||||
}, "balance_sats", decrement)
|
||||
if (!res.affected) {
|
||||
throw new Error("unaffected balance decrement for " + userId) // TODO: fix logs doxing
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue