Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
76e354c6ff | ||
|
|
3a78ef416a |
@@ -1,10 +1,4 @@
|
||||
bot:
|
||||
socks_proxy:
|
||||
host: 127.0.0.1:9996
|
||||
username: test
|
||||
password: username
|
||||
tor_proxy:
|
||||
host: 127.0.0.1:9050
|
||||
http_proxy: ""
|
||||
lnurl_public_host_name: "mylnurl.com"
|
||||
lnurl_server: "https://mylnurl.com"
|
||||
|
||||
@@ -5,9 +5,9 @@ go 1.17
|
||||
require (
|
||||
github.com/BurntSushi/toml v0.3.1
|
||||
github.com/PuerkitoBio/goquery v1.8.0
|
||||
github.com/btcsuite/btcd/btcec/v2 v2.2.0
|
||||
github.com/btcsuite/btcd v0.20.1-beta.0.20200515232429-9f0179fd2c46
|
||||
github.com/eko/gocache v1.2.0
|
||||
github.com/fiatjaf/go-lnurl v1.11.2
|
||||
github.com/fiatjaf/go-lnurl v1.8.4
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0
|
||||
github.com/gorilla/mux v1.8.0
|
||||
github.com/imroc/req v0.3.0
|
||||
@@ -17,79 +17,17 @@ require (
|
||||
github.com/nicksnyder/go-i18n/v2 v2.1.2
|
||||
github.com/orcaman/concurrent-map v1.0.0
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible
|
||||
github.com/sirupsen/logrus v1.7.0
|
||||
github.com/sethvargo/go-limiter v0.7.2
|
||||
github.com/sirupsen/logrus v1.6.0
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
||||
github.com/tidwall/buntdb v1.2.7
|
||||
github.com/tidwall/gjson v1.12.1
|
||||
github.com/tidwall/sjson v1.2.4
|
||||
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f
|
||||
golang.org/x/text v0.3.7
|
||||
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba
|
||||
golang.org/x/text v0.3.6
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0
|
||||
gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220326213923-f323bb71ac8e
|
||||
gorm.io/driver/sqlite v1.1.4
|
||||
gorm.io/gorm v1.21.12
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/XiaoMi/pegasus-go-client v0.0.0-20210427083443-f3b6b08bc4c2 // indirect
|
||||
github.com/aead/siphash v1.0.1 // indirect
|
||||
github.com/andybalholm/cascadia v1.3.1 // indirect
|
||||
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b // indirect
|
||||
github.com/btcsuite/btcd v0.23.1 // indirect
|
||||
github.com/btcsuite/btcd/btcutil v1.1.1 // indirect
|
||||
github.com/btcsuite/btcd/btcutil/psbt v1.1.4 // indirect
|
||||
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 // indirect
|
||||
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f // indirect
|
||||
github.com/btcsuite/btcwallet v0.15.1 // indirect
|
||||
github.com/btcsuite/btcwallet/wallet/txauthor v1.2.3 // indirect
|
||||
github.com/btcsuite/btcwallet/wallet/txrules v1.2.0 // indirect
|
||||
github.com/btcsuite/btcwallet/wallet/txsizes v1.1.0 // indirect
|
||||
github.com/btcsuite/btcwallet/walletdb v1.4.0 // indirect
|
||||
github.com/btcsuite/btcwallet/wtxmgr v1.5.0 // indirect
|
||||
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd // indirect
|
||||
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792 // indirect
|
||||
github.com/cenkalti/backoff/v4 v4.1.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.1.1 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/decred/dcrd/crypto/blake256 v1.0.0 // indirect
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect
|
||||
github.com/decred/dcrd/lru v1.0.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/go-errors/errors v1.0.1 // indirect
|
||||
github.com/go-redis/redis/v8 v8.8.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.2 // indirect
|
||||
github.com/kkdai/bstream v1.0.0 // indirect
|
||||
github.com/lightninglabs/gozmq v0.0.0-20191113021534-d20a764486bf // indirect
|
||||
github.com/lightninglabs/neutrino v0.14.2 // indirect
|
||||
github.com/lightningnetwork/lnd v0.15.0-beta // indirect
|
||||
github.com/lightningnetwork/lnd/clock v1.1.0 // indirect
|
||||
github.com/lightningnetwork/lnd/queue v1.1.0 // indirect
|
||||
github.com/lightningnetwork/lnd/ticker v1.1.0 // indirect
|
||||
github.com/lightningnetwork/lnd/tlv v1.0.3 // indirect
|
||||
github.com/lightningnetwork/lnd/tor v1.0.1 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.5 // indirect
|
||||
github.com/miekg/dns v1.1.43 // indirect
|
||||
github.com/nbd-wtf/ln-decodepay v1.5.1 // indirect
|
||||
github.com/pegasus-kv/thrift v0.13.0 // indirect
|
||||
github.com/spf13/cast v1.3.1 // indirect
|
||||
github.com/tidwall/btree v0.6.1 // indirect
|
||||
github.com/tidwall/grect v0.1.3 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.0 // indirect
|
||||
github.com/tidwall/rtred v0.1.2 // indirect
|
||||
github.com/tidwall/tinyqueue v0.1.1 // indirect
|
||||
go.opentelemetry.io/otel v0.20.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v0.20.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v0.20.0 // indirect
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect
|
||||
golang.org/x/sys v0.0.0-20220817070843-5a390386f1f2 // indirect
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
|
||||
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
k8s.io/apimachinery v0.0.0-20191123233150-4c4803ed55e3 // indirect
|
||||
)
|
||||
|
||||
// replace gopkg.in/lightningtipbot/telebot.v2 => ../telebot
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
package api
|
||||
|
||||
type BalanceResponse struct {
|
||||
Balance int64 `json:"balance"`
|
||||
}
|
||||
|
||||
type InvoiceStatusResponse struct {
|
||||
State string `json:"state,omitempty"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Preimage int64 `json:"preimage"`
|
||||
}
|
||||
|
||||
type CreateInvoiceResponse struct {
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
PayRequest string `json:"pay_request"`
|
||||
Preimage string `json:"preimage,omitempty"`
|
||||
}
|
||||
type CreateInvoiceRequest struct {
|
||||
Memo string `json:"memo"`
|
||||
Amount int64 `json:"amount"`
|
||||
DescriptionHash string `json:"description_hash"`
|
||||
UnhashedDescription string `json:"unhashed_description"`
|
||||
}
|
||||
|
||||
type PayInvoiceRequest struct {
|
||||
PayRequest string `json:"pay_req"`
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
Bot *telegram.TipBot
|
||||
}
|
||||
|
||||
type ErrorResponse struct {
|
||||
Message string `json:"error"`
|
||||
}
|
||||
|
||||
func RespondError(w http.ResponseWriter, message string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
json.NewEncoder(w).Encode(ErrorResponse{Message: message})
|
||||
}
|
||||
|
||||
func (s Service) Balance(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
balance, err := s.Bot.GetUserBalance(user)
|
||||
if err != nil {
|
||||
RespondError(w, "balance check failed")
|
||||
return
|
||||
}
|
||||
|
||||
balanceResponse := BalanceResponse{
|
||||
Balance: balance,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(balanceResponse)
|
||||
}
|
||||
|
||||
func (s Service) CreateInvoice(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
var createInvoiceRequest CreateInvoiceRequest
|
||||
err := json.NewDecoder(r.Body).Decode(&createInvoiceRequest)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Amount: createInvoiceRequest.Amount,
|
||||
Out: false,
|
||||
DescriptionHash: createInvoiceRequest.DescriptionHash,
|
||||
UnhashedDescription: createInvoiceRequest.UnhashedDescription,
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
s.Bot.Client)
|
||||
if err != nil {
|
||||
RespondError(w, "could not create invoice")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(invoice)
|
||||
}
|
||||
|
||||
func (s Service) PayInvoice(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
var payInvoiceRequest PayInvoiceRequest
|
||||
err := json.NewDecoder(r.Body).Decode(&payInvoiceRequest)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: payInvoiceRequest.PayRequest}, s.Bot.Client)
|
||||
if err != nil {
|
||||
RespondError(w, "could not pay invoice: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
payment, _ := s.Bot.Client.Payment(*user.Wallet, invoice.PaymentHash)
|
||||
if err != nil {
|
||||
// we assume that it's paid since thre was no error earlier
|
||||
payment.Paid = true
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(payment)
|
||||
}
|
||||
|
||||
func (s Service) PaymentStatus(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
payment_hash := mux.Vars(r)["payment_hash"]
|
||||
payment, err := s.Bot.Client.Payment(*user.Wallet, payment_hash)
|
||||
if err != nil {
|
||||
RespondError(w, "could not get payment")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(payment)
|
||||
}
|
||||
|
||||
// InvoiceStatus
|
||||
func (s Service) InvoiceStatus(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
payment_hash := mux.Vars(r)["payment_hash"]
|
||||
user.Wallet = &lnbits.Wallet{}
|
||||
payment, err := s.Bot.Client.Payment(*user.Wallet, payment_hash)
|
||||
if err != nil {
|
||||
RespondError(w, "could not get invoice")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(payment)
|
||||
}
|
||||
@@ -1,16 +1,8 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"gorm.io/gorm"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
@@ -24,82 +16,6 @@ func LoggingMiddleware(prefix string, next http.HandlerFunc) http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
type AuthType struct {
|
||||
Type string
|
||||
Decoder func(s string) ([]byte, error)
|
||||
}
|
||||
|
||||
var AuthTypeBasic = AuthType{Type: "Basic"}
|
||||
var AuthTypeBearerBase64 = AuthType{Type: "Basic", Decoder: base64.StdEncoding.DecodeString}
|
||||
|
||||
func AuthorizationMiddleware(database *gorm.DB, authType AuthType, next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
auth := r.Header.Get("Authorization")
|
||||
// check if the user is banned
|
||||
if auth == "" {
|
||||
w.WriteHeader(401)
|
||||
log.Warn("[AuthorizationMiddleware] no auth")
|
||||
return
|
||||
}
|
||||
_, password, ok := parseAuth(authType, auth)
|
||||
if !ok {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
// first we make sure that the password is not already "banned_"
|
||||
if strings.Contains(password, "_") || strings.HasPrefix(password, "banned_") {
|
||||
w.WriteHeader(401)
|
||||
log.Warnf("[AuthorizationMiddleware] Banned user %s. Not forwarding request", password)
|
||||
return
|
||||
}
|
||||
// then we check whether the "normal" password provided is in the database (it should be not if the user is banned)
|
||||
user := &lnbits.User{}
|
||||
tx := database.Where("wallet_adminkey = ? COLLATE NOCASE", password).First(user)
|
||||
if tx.Error != nil {
|
||||
tx = database.Where("wallet_inkey = ? COLLATE NOCASE", password).First(user)
|
||||
log.Warnf("[AuthorizationMiddleware] Could not get wallet admin key %s: %v", password, tx.Error)
|
||||
if tx.Error != nil {
|
||||
log.Warnf("[AuthorizationMiddleware] need admin key to pay invoice %s: %v", password, tx.Error)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/payinvoice" {
|
||||
log.Warnf("[AuthorizationMiddleware] need admin key to pay invoice %s: %v", password, tx.Error)
|
||||
return
|
||||
}
|
||||
}
|
||||
log.Debugf("[AuthorizationMiddleware] User: %s", telegram.GetUserStr(user.Telegram))
|
||||
r = r.WithContext(context.WithValue(r.Context(), "user", user))
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
// parseAuth parses an HTTP Basic Authentication string.
|
||||
// "Bearer QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
|
||||
func parseAuth(authType AuthType, auth string) (username, password string, ok bool) {
|
||||
parse := func(prefix string) (username, password string, ok bool) {
|
||||
// Case insensitive prefix match. See Issue 22736.
|
||||
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
|
||||
return
|
||||
}
|
||||
if authType.Decoder != nil {
|
||||
c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
cs := string(c)
|
||||
s := strings.IndexByte(cs, ':')
|
||||
if s < 0 {
|
||||
return
|
||||
}
|
||||
return cs[:s], cs[s+1:], true
|
||||
}
|
||||
return auth[len(prefix):], auth[len(prefix):], true
|
||||
|
||||
}
|
||||
return parse(fmt.Sprintf("%s ", authType.Type))
|
||||
|
||||
}
|
||||
|
||||
func dump(r *http.Request) string {
|
||||
x, err := httputil.DumpRequest(r, true)
|
||||
if err != nil {
|
||||
|
||||
@@ -2,7 +2,6 @@ package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"gorm.io/gorm"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
@@ -43,12 +42,6 @@ func (w *Server) ListenAndServe() {
|
||||
func (w *Server) PathPrefix(path string, handler http.Handler) {
|
||||
w.router.PathPrefix(path).Handler(handler)
|
||||
}
|
||||
func (w *Server) AppendAuthorizedRoute(path string, authType AuthType, database *gorm.DB, handler func(http.ResponseWriter, *http.Request), methods ...string) {
|
||||
r := w.router.HandleFunc(path, LoggingMiddleware("API", AuthorizationMiddleware(database, authType, handler)))
|
||||
if len(methods) > 0 {
|
||||
r.Methods(methods...)
|
||||
}
|
||||
}
|
||||
func (w *Server) AppendRoute(path string, handler func(http.ResponseWriter, *http.Request), methods ...string) {
|
||||
r := w.router.HandleFunc(path, LoggingMiddleware("API", handler))
|
||||
if len(methods) > 0 {
|
||||
|
||||
@@ -5,15 +5,12 @@
|
||||
<!DOCTYPE html>
|
||||
<meta charset="utf-8" />
|
||||
<meta property="og:title" content="Pay to {{.Username}}@ln.tips">
|
||||
<meta property="og:site_name" content="{{.Username}}@ln.tips">
|
||||
<meta property="og:description" content="Send bitcoin to {{.Username}} over Lightning. Get your own Lightning address at https://ln.tips 👈">
|
||||
<meta property="og:type" content="article" />
|
||||
<meta property="og:image" content="{{.Image}}">
|
||||
<meta property="og:image" content="https://avatars.githubusercontent.com/u/88730856?v=7">
|
||||
<meta property="og:url" content="https://ln.tips/@{{.Username}}">
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
<meta name="twitter:image:alt" content="Pay to {{.Username}}@ln.tips">
|
||||
<meta name="lightning" content="lnurlp:{{.Username}}@ln.tips"/>
|
||||
|
||||
<title>{{.Username}}@ln.tips</title>
|
||||
<script src="https://unpkg.com/kjua@0.6.0/dist/kjua.min.js"></script>
|
||||
<style>
|
||||
@@ -40,10 +37,6 @@
|
||||
.white {
|
||||
color: #f3f3f3c5;
|
||||
}
|
||||
.sm {
|
||||
color: #f3f3f3c5;
|
||||
font-size: 1rem;
|
||||
}
|
||||
#qr {
|
||||
display: block;
|
||||
margin-top: 50px;
|
||||
@@ -55,7 +48,7 @@
|
||||
white-space: pre-wrap;
|
||||
word-wrap: break-word;
|
||||
word-break: break-all;
|
||||
font-size: 1.5rem;
|
||||
font-size: 23px;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -64,7 +57,7 @@
|
||||
|
||||
<div><a href="lightning:{{.LNURLPay}}" id="qr"></a></div>
|
||||
<div class="white" id="invoice">{{.LNURLPay}}</div>
|
||||
<div class="sm">Get your own Lightning address here: <a class="sm" href="https://ln.tips">ln.tips</a></div>
|
||||
|
||||
<script>
|
||||
qr.appendChild(
|
||||
kjua({
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
@@ -27,8 +26,6 @@ func New(b *telegram.TipBot) Service {
|
||||
}
|
||||
}
|
||||
|
||||
const botImage = "https://avatars.githubusercontent.com/u/88730856?v=7"
|
||||
|
||||
//go:embed static
|
||||
var templates embed.FS
|
||||
var tmpl = template.Must(template.ParseFS(templates, "static/userpage.html"))
|
||||
@@ -40,7 +37,7 @@ var Client = &http.Client{
|
||||
// thank you fiatjaf for this code
|
||||
func (s Service) getTelegramUserPictureURL(username string) (string, error) {
|
||||
// with proxy:
|
||||
// client, err := s.network.GetHttpClient()
|
||||
// client, err := s.bot.GetHttpClient()
|
||||
// if err != nil {
|
||||
// return "", err
|
||||
// }
|
||||
@@ -68,7 +65,7 @@ func (s Service) getTelegramUserPictureURL(username string) (string, error) {
|
||||
|
||||
func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// https://ln.tips/.well-known/lnurlp/<username>
|
||||
username := strings.ToLower(mux.Vars(r)["username"])
|
||||
username := mux.Vars(r)["username"]
|
||||
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, username)
|
||||
log.Infof("[UserPage] rendering page of %s", username)
|
||||
lnurlEncode, err := lnurl.LNURLEncode(callback)
|
||||
@@ -77,11 +74,10 @@ func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
image, err := s.getTelegramUserPictureURL(username)
|
||||
if err != nil || image == "https://telegram.org/img/t_logo.png" {
|
||||
// replace the default image
|
||||
image = botImage
|
||||
if err != nil {
|
||||
log.Errorln("[UserPage]", err)
|
||||
image = "https://telegram.org/img/t_logo.png"
|
||||
}
|
||||
|
||||
if err := tmpl.ExecuteTemplate(w, "userpage", struct {
|
||||
Username string
|
||||
Image string
|
||||
|
||||
+6
-13
@@ -16,20 +16,13 @@ var Configuration = struct {
|
||||
Lnbits LnbitsConfiguration `yaml:"lnbits"`
|
||||
}{}
|
||||
|
||||
type SocksConfiguration struct {
|
||||
Host string `yaml:"host"`
|
||||
Username string `yaml:"username"`
|
||||
Password string `yaml:"password"`
|
||||
}
|
||||
|
||||
type BotConfiguration struct {
|
||||
SocksProxy *SocksConfiguration `yaml:"socks_proxy,omitempty"`
|
||||
TorProxy *SocksConfiguration `yaml:"tor_proxy,omitempty"`
|
||||
LNURLServer string `yaml:"lnurl_server"`
|
||||
LNURLServerUrl *url.URL `yaml:"-"`
|
||||
LNURLHostName string `yaml:"lnurl_public_host_name"`
|
||||
LNURLHostUrl *url.URL `yaml:"-"`
|
||||
LNURLSendImage bool `yaml:"lnurl_image"`
|
||||
HttpProxy string `yaml:"http_proxy"`
|
||||
LNURLServer string `yaml:"lnurl_server"`
|
||||
LNURLServerUrl *url.URL `yaml:"-"`
|
||||
LNURLHostName string `yaml:"lnurl_public_host_name"`
|
||||
LNURLHostUrl *url.URL `yaml:"-"`
|
||||
LNURLSendImage bool `yaml:"lnurl_image"`
|
||||
}
|
||||
|
||||
type TelegramConfiguration struct {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package lnbits
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/imroc/req"
|
||||
@@ -85,7 +84,7 @@ func (c *Client) CreateWallet(userId, walletName, adminId string) (wal Wallet, e
|
||||
}
|
||||
|
||||
// Invoice creates an invoice associated with this wallet.
|
||||
func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx Invoice, err error) {
|
||||
func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx BitInvoice, err error) {
|
||||
// custom header with invoice key
|
||||
invoiceHeader := req.Header{
|
||||
"Content-Type": "application/json",
|
||||
@@ -132,7 +131,7 @@ func (c Client) Info(w Wallet) (wtx Wallet, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// Payments returns wallet payments
|
||||
// Info returns wallet payments
|
||||
func (c Client) Payments(w Wallet) (wtx Payments, err error) {
|
||||
// custom header with invoice key
|
||||
invoiceHeader := req.Header{
|
||||
@@ -156,30 +155,6 @@ func (c Client) Payments(w Wallet) (wtx Payments, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// Payment state of a payment
|
||||
func (c Client) Payment(w Wallet, payment_hash string) (payment LNbitsPayment, err error) {
|
||||
// custom header with invoice key
|
||||
invoiceHeader := req.Header{
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
"X-Api-Key": w.Inkey,
|
||||
}
|
||||
resp, err := req.Get(c.url+fmt.Sprintf("/api/v1/payments/%s", payment_hash), invoiceHeader, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if resp.Response().StatusCode >= 300 {
|
||||
var reqErr Error
|
||||
resp.ToJSON(&reqErr)
|
||||
err = reqErr
|
||||
return
|
||||
}
|
||||
|
||||
err = resp.ToJSON(&payment)
|
||||
return
|
||||
}
|
||||
|
||||
// Wallets returns all wallets belonging to an user
|
||||
func (c Client) Wallets(w User) (wtx []Wallet, err error) {
|
||||
resp, err := req.Get(c.url+"/usermanager/api/v1/wallets/"+w.ID, c.header, nil)
|
||||
@@ -199,7 +174,7 @@ func (c Client) Wallets(w User) (wtx []Wallet, err error) {
|
||||
}
|
||||
|
||||
// Pay pays a given invoice with funds from the wallet.
|
||||
func (w Wallet) Pay(params PaymentParams, c *Client) (wtx Invoice, err error) {
|
||||
func (w Wallet) Pay(params PaymentParams, c *Client) (wtx BitInvoice, err error) {
|
||||
// custom header with admin key
|
||||
adminHeader := req.Header{
|
||||
"Content-Type": "application/json",
|
||||
|
||||
+18
-25
@@ -7,8 +7,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/satdress"
|
||||
"github.com/btcsuite/btcd/btcec/v2"
|
||||
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
|
||||
"github.com/btcsuite/btcd/btcec"
|
||||
|
||||
"github.com/imroc/req"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
@@ -75,12 +74,11 @@ func (u *User) ResetState() {
|
||||
}
|
||||
|
||||
type InvoiceParams struct {
|
||||
Out bool `json:"out"` // must be True if invoice is payed, False if invoice is received
|
||||
Amount int64 `json:"amount"` // amount in Satoshi
|
||||
Memo string `json:"memo,omitempty"` // the invoice memo.
|
||||
Webhook string `json:"webhook,omitempty"` // the webhook to fire back to when payment is received.
|
||||
DescriptionHash string `json:"description_hash,omitempty"` // the invoice description hash.
|
||||
UnhashedDescription string `json:"unhashed_description,omitempty"` // the unhashed invoice description.
|
||||
Out bool `json:"out"` // must be True if invoice is payed, False if invoice is received
|
||||
Amount int64 `json:"amount"` // amount in MilliSatoshi
|
||||
Memo string `json:"memo,omitempty"` // the invoice memo.
|
||||
Webhook string `json:"webhook,omitempty"` // the webhook to fire back to when payment is received.
|
||||
DescriptionHash string `json:"description_hash,omitempty"` // the invoice description hash.
|
||||
}
|
||||
|
||||
type PaymentParams struct {
|
||||
@@ -102,11 +100,14 @@ type TransferParams struct {
|
||||
}
|
||||
|
||||
type Error struct {
|
||||
Detail string `json:"detail"`
|
||||
Name string `json:"name"`
|
||||
Message string `json:"message"`
|
||||
Code int `json:"code"`
|
||||
Status int `json:"status"`
|
||||
}
|
||||
|
||||
func (err Error) Error() string {
|
||||
return err.Detail
|
||||
return err.Message
|
||||
}
|
||||
|
||||
type Wallet struct {
|
||||
@@ -118,11 +119,11 @@ type Wallet struct {
|
||||
User string `json:"user"`
|
||||
}
|
||||
|
||||
type Payment struct {
|
||||
type Payments []struct {
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending bool `json:"pending"`
|
||||
Amount int64 `json:"amount"`
|
||||
Fee int64 `json:"fee"`
|
||||
Amount int `json:"amount"`
|
||||
Fee int `json:"fee"`
|
||||
Memo string `json:"memo"`
|
||||
Time int `json:"time"`
|
||||
Bolt11 string `json:"bolt11"`
|
||||
@@ -134,25 +135,17 @@ type Payment struct {
|
||||
WebhookStatus interface{} `json:"webhook_status"`
|
||||
}
|
||||
|
||||
type LNbitsPayment struct {
|
||||
Paid bool `json:"paid"`
|
||||
Preimage string `json:"preimage"`
|
||||
Details Payment `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
type Payments []Payment
|
||||
|
||||
type Invoice struct {
|
||||
type BitInvoice struct {
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
PaymentRequest string `json:"payment_request"`
|
||||
}
|
||||
|
||||
// from fiatjaf/lnurl-go
|
||||
func (u User) LinkingKey(domain string) (*btcec.PrivateKey, *btcec.PublicKey) {
|
||||
seedHash := sha256.Sum256([]byte(
|
||||
seedhash := sha256.Sum256([]byte(
|
||||
fmt.Sprintf("lnurlkeyseed:%s:%s",
|
||||
domain, u.ID)))
|
||||
return btcec.PrivKeyFromBytes(seedHash[:])
|
||||
return btcec.PrivKeyFromBytes(btcec.S256(), seedhash[:])
|
||||
}
|
||||
|
||||
func (u User) SignKeyAuth(domain string, k1hex string) (key string, sig string, err error) {
|
||||
@@ -164,7 +157,7 @@ func (u User) SignKeyAuth(domain string, k1hex string) (key string, sig string,
|
||||
return "", "", fmt.Errorf("invalid k1 hex '%s': %w", k1hex, err)
|
||||
}
|
||||
|
||||
signature := ecdsa.Sign(sk, k1)
|
||||
signature, err := sk.Sign(k1)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("error signing k1: %w", err)
|
||||
}
|
||||
|
||||
@@ -229,7 +229,7 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
|
||||
payerDataByte = []byte("")
|
||||
}
|
||||
|
||||
descriptionHash, err := w.DescriptionHash(metadata, string(payerDataByte))
|
||||
descriptionHash, err := w.descriptionHash(metadata, string(payerDataByte))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -281,8 +281,8 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
|
||||
|
||||
}
|
||||
|
||||
// DescriptionHash is the SHA256 hash of the metadata
|
||||
func (w Lnurl) DescriptionHash(metadata lnurl.Metadata, payerData string) (string, error) {
|
||||
// descriptionHash is the SHA256 hash of the metadata
|
||||
func (w Lnurl) descriptionHash(metadata lnurl.Metadata, payerData string) (string, error) {
|
||||
var hashString string
|
||||
var hash [32]byte
|
||||
if len(payerData) == 0 {
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
package network
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
type ClientType string
|
||||
|
||||
const (
|
||||
ClientTypeClearNet = "clearnet"
|
||||
ClientTypeTor = "tor"
|
||||
)
|
||||
|
||||
func GetClient(clientType ClientType) (*http.Client, error) {
|
||||
client := http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
var cfg *internal.SocksConfiguration
|
||||
switch clientType {
|
||||
case ClientTypeClearNet:
|
||||
cfg = internal.Configuration.Bot.SocksProxy
|
||||
case ClientTypeTor:
|
||||
cfg = internal.Configuration.Bot.TorProxy
|
||||
default:
|
||||
return nil, fmt.Errorf("[GetClient] invalid clientType")
|
||||
}
|
||||
if cfg == nil {
|
||||
return &client, nil
|
||||
}
|
||||
proxyURL, _ := url.Parse(cfg.Host)
|
||||
specialTransport := &http.Transport{}
|
||||
specialTransport.Proxy = http.ProxyURL(proxyURL)
|
||||
var auth *proxy.Auth
|
||||
if cfg.Username != "" && cfg.Password != "" {
|
||||
auth = &proxy.Auth{User: cfg.Username, Password: cfg.Password}
|
||||
}
|
||||
d, err := proxy.SOCKS5("tcp", cfg.Host, auth, &net.Dialer{
|
||||
Timeout: 20 * time.Second,
|
||||
Deadline: time.Now().Add(time.Second * 10),
|
||||
KeepAlive: -1,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return &client, nil
|
||||
}
|
||||
specialTransport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return d.Dial(network, addr)
|
||||
}
|
||||
client.Transport = specialTransport
|
||||
return &client, nil
|
||||
}
|
||||
@@ -8,20 +8,27 @@ import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/network"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
// Much of this is from github.com/fiatjaf/makeinvoice
|
||||
// but with added "checkInvoice" and http proxy support
|
||||
|
||||
var HttpProxyURL = internal.Configuration.Bot.HttpProxy
|
||||
|
||||
var Client = &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
type LNDParams struct {
|
||||
Cert []byte `json:"cert" gorm:"-"`
|
||||
CertString string `json:"certstring"`
|
||||
@@ -65,50 +72,37 @@ type CheckInvoiceParams struct {
|
||||
Status string
|
||||
}
|
||||
|
||||
func SetupHttpClient(useProxy bool, cert []byte) (*http.Client, error) {
|
||||
var client *http.Client
|
||||
if !useProxy {
|
||||
client = &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
} else {
|
||||
var err error
|
||||
client, err = network.GetClient(network.ClientTypeTor)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
}
|
||||
// use a cert or skip TLS verification?
|
||||
if len(cert) > 0 {
|
||||
caCertPool := x509.NewCertPool()
|
||||
ok := caCertPool.AppendCertsFromPEM(cert)
|
||||
if !ok {
|
||||
return client, fmt.Errorf("invalid root certificate")
|
||||
}
|
||||
client.Transport.(*http.Transport).TLSClientConfig = &tls.Config{RootCAs: caCertPool}
|
||||
} else {
|
||||
client.Transport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func MakeInvoice(params Params) (CheckInvoiceParams, error) {
|
||||
// defer func(prevTransport http.RoundTripper) {
|
||||
// Client.Transport = prevTransport
|
||||
// }(Client.Transport)
|
||||
defer func(prevTransport http.RoundTripper) {
|
||||
Client.Transport = prevTransport
|
||||
}(Client.Transport)
|
||||
|
||||
if params.Backend == nil {
|
||||
return CheckInvoiceParams{}, errors.New("no backend specified")
|
||||
}
|
||||
|
||||
var err error
|
||||
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
|
||||
if err != nil {
|
||||
log.Errorf(err.Error())
|
||||
return CheckInvoiceParams{}, err
|
||||
specialTransport := &http.Transport{}
|
||||
|
||||
// use a cert or skip TLS verification?
|
||||
if len(params.Backend.getCert()) > 0 {
|
||||
caCertPool := x509.NewCertPool()
|
||||
ok := caCertPool.AppendCertsFromPEM([]byte(params.Backend.getCert()))
|
||||
if !ok {
|
||||
return CheckInvoiceParams{}, fmt.Errorf("invalid root certificate")
|
||||
}
|
||||
specialTransport.TLSClientConfig = &tls.Config{RootCAs: caCertPool}
|
||||
} else {
|
||||
specialTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
|
||||
}
|
||||
|
||||
// use a proxy?
|
||||
if !params.Backend.isLocal() && len(HttpProxyURL) > 0 {
|
||||
proxyURL, _ := url.Parse(HttpProxyURL)
|
||||
specialTransport.Proxy = http.ProxyURL(proxyURL)
|
||||
}
|
||||
|
||||
Client.Transport = specialTransport
|
||||
|
||||
// description hash?
|
||||
var hexh, b64h string
|
||||
if params.DescriptionHash != nil {
|
||||
@@ -167,9 +161,6 @@ func MakeInvoice(params Params) (CheckInvoiceParams, error) {
|
||||
Hash: []byte(gjson.ParseBytes(b).Get("r_hash").String()),
|
||||
Status: "OPEN",
|
||||
}
|
||||
if len(checkInvoiceParams.PR) == 0 {
|
||||
return CheckInvoiceParams{}, errors.New("could not create invoice")
|
||||
}
|
||||
return checkInvoiceParams, nil
|
||||
|
||||
case LNBitsParams:
|
||||
@@ -220,9 +211,6 @@ func MakeInvoice(params Params) (CheckInvoiceParams, error) {
|
||||
Hash: []byte(gjson.ParseBytes(b).Get("payment_hash").String()),
|
||||
Status: "OPEN",
|
||||
}
|
||||
if len(checkInvoiceParams.PR) == 0 {
|
||||
return CheckInvoiceParams{}, errors.New("could not create invoice")
|
||||
}
|
||||
return checkInvoiceParams, nil
|
||||
default:
|
||||
return CheckInvoiceParams{}, errors.New("wrong backend type")
|
||||
@@ -230,21 +218,35 @@ func MakeInvoice(params Params) (CheckInvoiceParams, error) {
|
||||
}
|
||||
|
||||
func CheckInvoice(params CheckInvoiceParams) (CheckInvoiceParams, error) {
|
||||
// defer func(prevTransport http.RoundTripper) {
|
||||
// Client.Transport = prevTransport
|
||||
// }(Client.Transport)
|
||||
defer func(prevTransport http.RoundTripper) {
|
||||
Client.Transport = prevTransport
|
||||
}(Client.Transport)
|
||||
|
||||
if params.Backend == nil {
|
||||
return CheckInvoiceParams{}, errors.New("no backend specified")
|
||||
}
|
||||
specialTransport := &http.Transport{}
|
||||
|
||||
var err error
|
||||
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
|
||||
if err != nil {
|
||||
log.Errorf(err.Error())
|
||||
return CheckInvoiceParams{}, err
|
||||
// use a cert or skip TLS verification?
|
||||
if len(params.Backend.getCert()) > 0 {
|
||||
caCertPool := x509.NewCertPool()
|
||||
ok := caCertPool.AppendCertsFromPEM(params.Backend.getCert())
|
||||
if !ok {
|
||||
return CheckInvoiceParams{}, fmt.Errorf("invalid root certificate")
|
||||
}
|
||||
specialTransport.TLSClientConfig = &tls.Config{RootCAs: caCertPool}
|
||||
} else {
|
||||
specialTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
|
||||
}
|
||||
|
||||
// use a proxy?
|
||||
if !params.Backend.isLocal() && len(HttpProxyURL) > 0 {
|
||||
proxyURL, _ := url.Parse(HttpProxyURL)
|
||||
specialTransport.Proxy = http.ProxyURL(proxyURL)
|
||||
}
|
||||
|
||||
Client.Transport = specialTransport
|
||||
|
||||
switch backend := params.Backend.(type) {
|
||||
case LNDParams:
|
||||
log.Debugf("[CheckInvoice] LND invoice %s at %s", base64.StdEncoding.EncodeToString(params.Hash), backend.Host)
|
||||
@@ -327,4 +329,5 @@ func CheckInvoice(params CheckInvoiceParams) (CheckInvoiceParams, error) {
|
||||
default:
|
||||
return CheckInvoiceParams{}, errors.New("missing backend params")
|
||||
}
|
||||
return CheckInvoiceParams{}, errors.New("missing backend params")
|
||||
}
|
||||
|
||||
@@ -324,7 +324,7 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
|
||||
bot.trySendMessage(ticketEvent.Payer.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupClickToJoinMessage"), resp.Result.InviteLink, ticketEvent.Group.Title))
|
||||
|
||||
// send a notification to the group that sold the ticket
|
||||
bot.trySendMessage(&tb.Chat{ID: ticketEvent.Group.ID}, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupTicketIssuedGroupMessage"), GetUserStrMd(ticketEvent.Payer.Telegram)))
|
||||
bot.trySendMessage(&tb.Chat{ID: ticketEvent.Group.ID}, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupTicketIssuedGroupMessage"), GetUserStr(ticketEvent.Payer.Telegram)))
|
||||
|
||||
// take a commission
|
||||
ticketSat := ticketEvent.Group.Ticket.Price
|
||||
@@ -366,9 +366,9 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", GetUserStr(ticketEvent.Payer.Telegram))
|
||||
log.Errorln(errmsg)
|
||||
}
|
||||
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupReceiveTicketInvoiceCommission"), ticketSat, commissionSat, ticketEvent.Group.Title, GetUserStrMd(ticketEvent.Payer.Telegram)))
|
||||
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupReceiveTicketInvoiceCommission"), ticketSat, commissionSat, ticketEvent.Group.Title, GetUserStr(ticketEvent.Payer.Telegram)))
|
||||
} else {
|
||||
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupReceiveTicketInvoice"), ticketSat, ticketEvent.Group.Title, GetUserStrMd(ticketEvent.Payer.Telegram)))
|
||||
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupReceiveTicketInvoice"), ticketSat, ticketEvent.Group.Title, GetUserStr(ticketEvent.Payer.Telegram)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
@@ -61,11 +60,11 @@ func (bot TipBot) makeAdvancedHelpMessage(ctx context.Context, m *tb.Message) st
|
||||
// we print the anonymous ln address in the advanced help
|
||||
lnaddr, err := bot.UserGetAnonLightningAddress(fromUser)
|
||||
if err == nil {
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Anonymous Lightning address: `%s`\n", lnaddr)
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Anonymous lightning address: `%s`\n", lnaddr)
|
||||
}
|
||||
lnurl, err := UserGetAnonLNURL(fromUser)
|
||||
lnurl, err := UserGetLNURL(fromUser)
|
||||
if err == nil {
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Anonymous LNURL: `%s`", lnurl)
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("LNURL: `%s`", lnurl)
|
||||
}
|
||||
|
||||
// this is so stupid:
|
||||
|
||||
@@ -3,9 +3,8 @@ package telegram
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
|
||||
@@ -53,7 +52,7 @@ func (bot *TipBot) lndhubHandler(ctx intercept.Context) (intercept.Context, erro
|
||||
go func() {
|
||||
time.Sleep(time.Second * 60)
|
||||
bot.tryDeleteMessage(linkmsg)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "linkHiddenMessage"), tb.Silent)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "linkHiddenMessage"))
|
||||
}()
|
||||
// auto delete the message
|
||||
// NewMessage(linkmsg, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
|
||||
|
||||
@@ -4,10 +4,8 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/network"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"net/url"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
@@ -107,7 +105,7 @@ func (bot *TipBot) confirmLnurlAuthHandler(ctx intercept.Context) (intercept.Con
|
||||
}
|
||||
|
||||
var sentsigres lnurl.LNURLResponse
|
||||
client, err := network.GetClient(network.ClientTypeClearNet)
|
||||
client, err := bot.GetHttpClient()
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/network"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
@@ -26,22 +23,21 @@ import (
|
||||
// LnurlPayState saves the state of the user for an LNURL payment
|
||||
type LnurlPayState struct {
|
||||
*storage.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
LNURLPayParams lnurl.LNURLPayParams `json:"LNURLPayParams"`
|
||||
LNURLPayValues lnurl.LNURLPayValues `json:"LNURLPayValues"`
|
||||
Amount int64 `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
DescriptionHash string `json:"descriptionHash,omitempty"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
From *lnbits.User `json:"from"`
|
||||
LNURLPayParams lnurl.LNURLPayParams `json:"LNURLPayParams"`
|
||||
LNURLPayValues lnurl.LNURLPayValues `json:"LNURLPayValues"`
|
||||
Amount int64 `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
}
|
||||
|
||||
// lnurlPayHandler is invoked when the first lnurl response was a lnurlpay response
|
||||
// lnurlPayHandler1 is invoked when the first lnurl response was a lnurlpay response
|
||||
// at this point, the user hans't necessarily entered an amount yet
|
||||
func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPayState) (context.Context, error) {
|
||||
func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPayState) {
|
||||
m := ctx.Message()
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, fmt.Errorf("user has no wallet")
|
||||
return
|
||||
}
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("lnurlp-%d-%s", m.Sender.ID, RandStringRunes(5))
|
||||
@@ -78,18 +74,11 @@ func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPaySta
|
||||
log.Warnf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), payParams.LNURLPayParams.MinSendable/1000, payParams.LNURLPayParams.MaxSendable/1000))
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
// set also amount in the state of the user
|
||||
payParams.Amount = amount * 1000 // save as mSat
|
||||
|
||||
// calculate description hash of the metadata and save it
|
||||
descriptionHash, err := bot.DescriptionHash(payParams.LNURLPayParams.Metadata, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payParams.DescriptionHash = descriptionHash
|
||||
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(payParams.Set(payParams, bot.Bunt))
|
||||
|
||||
@@ -100,7 +89,7 @@ func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPaySta
|
||||
} else if amount_err != nil || amount < 1 {
|
||||
// // no amount was entered, set user state and ask for amount
|
||||
bot.askForAmount(ctx, id, "LnurlPayState", payParams.LNURLPayParams.MinSendable, payParams.LNURLPayParams.MaxSendable, m.Text)
|
||||
return ctx, nil
|
||||
return
|
||||
}
|
||||
|
||||
// We need to save the pay state in the user state so we can load the payment in the next ctx
|
||||
@@ -108,12 +97,12 @@ func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPaySta
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
|
||||
// directly go to confirm
|
||||
bot.lnurlPayHandlerSend(ctx)
|
||||
return ctx, nil
|
||||
return
|
||||
}
|
||||
|
||||
// lnurlPayHandlerSend is invoked when the user has delivered an amount and is ready to pay
|
||||
@@ -154,7 +143,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
|
||||
|
||||
// LnurlPayState loaded
|
||||
|
||||
client, err := network.GetClient(network.ClientTypeClearNet)
|
||||
client, err := bot.GetHttpClient()
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
@@ -196,28 +185,11 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
|
||||
if len(response2.Reason) > 0 {
|
||||
error_reason = response2.Reason
|
||||
}
|
||||
log.Errorf("[lnurlPayHandlerSend] Error in LNURLPayValues: %s", error_reason)
|
||||
log.Errorf("[lnurlPayHandler] Error in LNURLPayValues: %s", error_reason)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
|
||||
return ctx, fmt.Errorf("error in LNURLPayValues: %s", error_reason)
|
||||
return ctx, fmt.Errorf("Error in LNURLPayValues: %s", error_reason)
|
||||
}
|
||||
|
||||
// todo: doesn't work with lnurls from lnbits??
|
||||
// check whether description hash matches with expected hash
|
||||
// decode invoice
|
||||
// bolt11, err := decodepay.Decodepay(response2.PR)
|
||||
// if err != nil {
|
||||
// bot.trySendMessage(ctx.Sender(), helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
|
||||
// errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err.Error())
|
||||
// log.Errorln(errmsg)
|
||||
// return ctx, errors.New(errors.InvalidSyntaxError, err)
|
||||
// }
|
||||
// if bolt11.DescriptionHash != lnurlPayState.DescriptionHash {
|
||||
// log.Errorf("[lnurlPayHandlerSend] Error: description hash doesn't match")
|
||||
// bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "description hash doesn't match.\nExpected: `"+lnurlPayState.DescriptionHash+"` Received: `"+bolt11.DescriptionHash+"`"))
|
||||
// return ctx, fmt.Errorf("description hash doesn't match")
|
||||
// }
|
||||
|
||||
// all good
|
||||
lnurlPayState.LNURLPayValues = response2
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
|
||||
|
||||
@@ -4,12 +4,10 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/network"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
@@ -42,7 +40,7 @@ type LnurlWithdrawState struct {
|
||||
Comment string `json:"comment"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
Success bool `json:"success"`
|
||||
Invoice lnbits.Invoice `json:"invoice"`
|
||||
Invoice lnbits.BitInvoice `json:"invoice"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
@@ -266,7 +264,7 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
|
||||
callbackUrl.RawQuery = qs.Encode()
|
||||
|
||||
// lnurlWithdrawState loaded
|
||||
client, err := network.GetClient(network.ClientTypeClearNet)
|
||||
client, err := bot.GetHttpClient()
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
|
||||
+26
-39
@@ -2,14 +2,13 @@ package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/network"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
@@ -24,7 +23,22 @@ import (
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
func (bot *TipBot) cancelLnUrlHandler(c *tb.Callback) {
|
||||
func (bot *TipBot) GetHttpClient() (*http.Client, error) {
|
||||
client := http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
if internal.Configuration.Bot.HttpProxy != "" {
|
||||
proxyUrl, err := url.Parse(internal.Configuration.Bot.HttpProxy)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return nil, err
|
||||
}
|
||||
client.Transport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)}
|
||||
}
|
||||
return &client, nil
|
||||
}
|
||||
|
||||
func (bot TipBot) cancelLnUrlHandler(c *tb.Callback) {
|
||||
}
|
||||
|
||||
// lnurlHandler is invoked on /lnurl command
|
||||
@@ -67,7 +81,7 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error
|
||||
// get rid of the URI prefix
|
||||
lnurlSplit = strings.TrimPrefix(lnurlSplit, "lightning:")
|
||||
|
||||
// log.Debugf("[lnurlHandler] lnurlSplit: %s", lnurlSplit)
|
||||
log.Debugf("[lnurlHandler] lnurlSplit: %s", lnurlSplit)
|
||||
// HandleLNURL by fiatjaf/go-lnurl
|
||||
_, params, err := bot.HandleLNURL(lnurlSplit)
|
||||
if err != nil {
|
||||
@@ -93,7 +107,7 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error
|
||||
if len(payParams.LNURLPayParams.Metadata.Image.Bytes) > 0 {
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{
|
||||
File: tb.File{FileReader: bytes.NewReader(payParams.LNURLPayParams.Metadata.Image.Bytes)},
|
||||
Caption: payParams.LNURLPayParams.Metadata.Description})
|
||||
Caption: fmt.Sprintf("%s", payParams.LNURLPayParams.Metadata.Description)})
|
||||
} else if len(payParams.LNURLPayParams.Metadata.Description) > 0 {
|
||||
// display the metadata text from the first LNURL-p response
|
||||
// if there was no photo in the last step
|
||||
@@ -135,6 +149,7 @@ func (bot *TipBot) UserGetAnonLightningAddress(user *lnbits.User) (string, error
|
||||
func UserGetLNURL(user *lnbits.User) (string, error) {
|
||||
name := fmt.Sprint(user.UUID)
|
||||
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, name)
|
||||
log.Debugf("[lnurlReceiveHandler] %s's LNURL: %s", GetUserStr(user.Telegram), callback)
|
||||
|
||||
lnurlEncode, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
@@ -143,17 +158,8 @@ func UserGetLNURL(user *lnbits.User) (string, error) {
|
||||
return lnurlEncode, nil
|
||||
}
|
||||
|
||||
func UserGetAnonLNURL(user *lnbits.User) (string, error) {
|
||||
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, fmt.Sprint(user.AnonIDSha256))
|
||||
lnurlEncode, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return lnurlEncode, nil
|
||||
}
|
||||
|
||||
// lnurlReceiveHandler outputs the LNURL of the user
|
||||
func (bot *TipBot) lnurlReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
func (bot TipBot) lnurlReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
fromUser := LoadUser(ctx)
|
||||
lnurlEncode, err := UserGetLNURL(fromUser)
|
||||
@@ -178,7 +184,7 @@ func (bot *TipBot) lnurlReceiveHandler(ctx intercept.Context) (intercept.Context
|
||||
}
|
||||
|
||||
// fiatjaf/go-lnurl 1.8.4 with proxy
|
||||
func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
|
||||
func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
|
||||
var err error
|
||||
var rawurl string
|
||||
|
||||
@@ -213,13 +219,8 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
// rerun LNURLDecode to convert lnurlp/keyauth schemes to https://
|
||||
rawurl, err = lnurl.LNURLDecode(rawurl)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
}
|
||||
log.Debug("[HandleLNURL] rawurl: ", rawurl)
|
||||
|
||||
parsed, err := url.Parse(rawurl)
|
||||
if err != nil {
|
||||
return rawurl, nil, err
|
||||
@@ -243,7 +244,7 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
|
||||
// return rawurl, nil, err
|
||||
// }
|
||||
|
||||
client, err := network.GetClient(network.ClientTypeClearNet)
|
||||
client, err := bot.GetHttpClient()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
@@ -280,20 +281,6 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
|
||||
// value, err := lnurl.HandleChannel(b)
|
||||
// return rawurl, value, err
|
||||
default:
|
||||
return rawurl, nil, fmt.Errorf("unkown LNURL response")
|
||||
return rawurl, nil, fmt.Errorf("Unkown LNURL response.")
|
||||
}
|
||||
}
|
||||
|
||||
// DescriptionHash is the SHA256 hash of the metadata
|
||||
func (bot *TipBot) DescriptionHash(metadata lnurl.Metadata, payerData string) (string, error) {
|
||||
var hashString string
|
||||
var hash [32]byte
|
||||
if len(payerData) == 0 {
|
||||
hash = sha256.Sum256([]byte(metadata.Encode()))
|
||||
hashString = hex.EncodeToString(hash[:])
|
||||
} else {
|
||||
hash = sha256.Sum256([]byte(metadata.Encode() + payerData))
|
||||
hashString = hex.EncodeToString(hash[:])
|
||||
}
|
||||
return hashString, nil
|
||||
}
|
||||
|
||||
@@ -23,8 +23,7 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
registerNodeMessage = "📖 Connect your Lightning node with your wallet.\n\nCurrently supported backends: `lnd` and `lnbits`\nTo register a node, type: `/node add <type> <info>`\n\n*LND (REST):* `/node add lnd <host> <macaroon> <cert>`\n*LNbits:* `/node add lnbits <host> <key>`\n\nℹ️ Always use `https://` for the `<host>`, even if you use a Tor node. Certificates and macaroons need to be in base64 format.\n\n⚠️ For security reasons, you should *only use an invoice macaroon* for LND and an *invoice key* for LNbits."
|
||||
nodeHelpMessage = "⚙️ *Commands:*\n`/node add <type> <info>` ✅ Add your node.\n`/node invoice <admount>` ⤵️ Fetch an invoice from your node.\n`/node proxy <amount>` 🔀 Proxy a payment to your node (privacy feature).\n`/node help` 📖 Show help."
|
||||
registerNodeMessage = "📖 You did not register a node yet.\n\nCurrently supported backends: `lnd` and `lnbits`\nTo register a node, type: `/node add <Type> <Node_info>`\n*LND:* `/node add lnd <Host> <Macaroon> <Cert>`\n*LNbits:* `/node add lnbits <Host> <Key>`\n\nFor security reasons, you should *only use an invoice macaroon* for LND and an *invoice key* for LNbits."
|
||||
checkingInvoiceMessage = "⏳ Checking invoice on your node..."
|
||||
invoiceNotSettledMessage = "❌ Invoice has not settled yet."
|
||||
checkInvoiceButtonMessage = "🔄 Check invoice"
|
||||
@@ -50,34 +49,29 @@ func parseUserSettingInput(ctx intercept.Context, m *tb.Message) (satdress.Backe
|
||||
if splitlen < 4 {
|
||||
return params, fmt.Errorf("not enough arguments")
|
||||
}
|
||||
switch strings.ToLower(splits[2]) {
|
||||
case "lnd":
|
||||
if splitlen < 5 || splitlen > 7 {
|
||||
return params, fmt.Errorf("wrong format. Use <Type> <Host> <Macaroon> [<Cert>]")
|
||||
if strings.ToLower(splits[2]) == "lnd" {
|
||||
if splitlen < 6 || splitlen > 7 {
|
||||
return params, fmt.Errorf("wrong format. Use <Type> <Host> <Macaroon> <Cert>")
|
||||
}
|
||||
host := splits[3]
|
||||
macaroon := splits[4]
|
||||
var pem []byte
|
||||
if splitlen == 6 {
|
||||
cert := splits[5]
|
||||
pem := parseCertificateToPem(cert)
|
||||
if len(pem) < 1 {
|
||||
return params, fmt.Errorf("certificate has invalid format")
|
||||
}
|
||||
}
|
||||
cert := splits[5]
|
||||
|
||||
hostsplit := strings.Split(host, ".")
|
||||
if len(hostsplit) == 0 {
|
||||
return params, fmt.Errorf("host has wrong format")
|
||||
}
|
||||
|
||||
pem := parseCertificateToPem(cert)
|
||||
if len(pem) < 1 {
|
||||
return params, fmt.Errorf("certificate has invalid format")
|
||||
}
|
||||
return satdress.LNDParams{
|
||||
Cert: pem,
|
||||
Host: host,
|
||||
Macaroon: macaroon,
|
||||
CertString: string(pem),
|
||||
}, nil
|
||||
case "lnbits":
|
||||
} else if strings.ToLower(splits[2]) == "lnbits" {
|
||||
if splitlen < 5 || splitlen > 6 {
|
||||
return params, fmt.Errorf("wrong format. Use <Type> <Host> <Key>")
|
||||
}
|
||||
@@ -93,9 +87,8 @@ func parseUserSettingInput(ctx intercept.Context, m *tb.Message) (satdress.Backe
|
||||
Host: host,
|
||||
Key: key,
|
||||
}, nil
|
||||
default:
|
||||
return params, fmt.Errorf("unknown backend type. Supported types: `lnd`, `lnbits`")
|
||||
}
|
||||
return params, fmt.Errorf("unknown backend type. Supported types: `lnd`, `lnbits`")
|
||||
}
|
||||
|
||||
func nodeInfoString(node *lnbits.NodeSettings) (string, error) {
|
||||
@@ -117,11 +110,6 @@ func nodeInfoString(node *lnbits.NodeSettings) (string, error) {
|
||||
return fmt.Sprintf("ℹ️ *Your node information.*\n\n%s", node_info_str_filled), nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) nodeHelpHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
bot.trySendMessage(ctx.Message().Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) getNodeHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
|
||||
@@ -131,14 +119,14 @@ func (bot *TipBot) getNodeHandler(ctx intercept.Context) (intercept.Context, err
|
||||
}
|
||||
|
||||
if user.Settings == nil {
|
||||
bot.trySendMessage(m.Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
|
||||
bot.trySendMessage(m.Sender, registerNodeMessage)
|
||||
return ctx, fmt.Errorf("no node registered")
|
||||
}
|
||||
|
||||
node_info_str, err := nodeInfoString(&user.Settings.Node)
|
||||
if err != nil {
|
||||
log.Infof("Could not get node info for user %s", GetUserStr(user.Telegram))
|
||||
bot.trySendMessage(m.Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
|
||||
bot.trySendMessage(m.Sender, registerNodeMessage)
|
||||
return ctx, err
|
||||
}
|
||||
bot.trySendMessage(m.Sender, node_info_str)
|
||||
@@ -152,17 +140,17 @@ func (bot *TipBot) nodeHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
if len(splits) == 1 {
|
||||
return bot.getNodeHandler(ctx)
|
||||
} else if len(splits) > 1 {
|
||||
switch strings.ToLower(splits[1]) {
|
||||
case "invoice":
|
||||
if splits[1] == "invoice" {
|
||||
return bot.invHandler(ctx)
|
||||
case "add":
|
||||
}
|
||||
if splits[1] == "add" {
|
||||
return bot.registerNodeHandler(ctx)
|
||||
case "check":
|
||||
}
|
||||
if splits[1] == "check" {
|
||||
return bot.satdressCheckInvoiceHandler(ctx)
|
||||
case "proxy":
|
||||
}
|
||||
if splits[1] == "proxy" {
|
||||
return bot.satdressProxyHandler(ctx)
|
||||
case "help":
|
||||
return bot.nodeHelpHandler(ctx)
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
@@ -228,12 +216,10 @@ func (bot *TipBot) registerNodeHandler(ctx intercept.Context) (intercept.Context
|
||||
node_info_str, err := nodeInfoString(&user.Settings.Node)
|
||||
if err != nil {
|
||||
log.Infof("Could not get node info for user %s", GetUserStr(user.Telegram))
|
||||
bot.trySendMessage(m.Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
|
||||
bot.trySendMessage(m.Sender, registerNodeMessage)
|
||||
return ctx, err
|
||||
}
|
||||
bot.tryEditMessage(check_message, fmt.Sprintf("%s\n\n%s", node_info_str, nodeAddedMessage))
|
||||
|
||||
log.Infof("[node:add] Added node of user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -256,13 +242,10 @@ func (bot *TipBot) invHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
}
|
||||
}
|
||||
|
||||
log.Infof("[node:invoice] Getting invoice for user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
|
||||
check_message := bot.trySendMessageEditable(user.Telegram, routingInvoiceMessage)
|
||||
var getInvoiceParams satdress.CheckInvoiceParams
|
||||
|
||||
switch user.Settings.Node.NodeType {
|
||||
case "lnd":
|
||||
if user.Settings.Node.NodeType == "lnd" {
|
||||
// get invoice from user's node
|
||||
getInvoiceParams, err = satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
@@ -275,7 +258,7 @@ func (bot *TipBot) invHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
Description: fmt.Sprintf("Invoice by %s", GetUserStr(bot.Telegram.Me)),
|
||||
},
|
||||
)
|
||||
case "lnbits":
|
||||
} else if user.Settings.Node.NodeType == "lnbits" {
|
||||
// get invoice from user's node
|
||||
getInvoiceParams, err = satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
@@ -287,8 +270,6 @@ func (bot *TipBot) invHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
Description: fmt.Sprintf("Invoice by %s", GetUserStr(bot.Telegram.Me)),
|
||||
},
|
||||
)
|
||||
default:
|
||||
return ctx, fmt.Errorf("unknown node type %s", user.Settings.Node.NodeType)
|
||||
}
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
@@ -311,8 +292,6 @@ func (bot *TipBot) invHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
// add the getInvoiceParams to cache to check it later
|
||||
bot.Cache.Set(fmt.Sprintf("invoice:%d", user.Telegram.ID), getInvoiceParams, &store.Options{Expiration: 24 * time.Hour})
|
||||
|
||||
log.Infof("[node:invoice] Invoice created for user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
|
||||
// check if invoice settles
|
||||
return bot.satdressCheckInvoiceHandler(ctx)
|
||||
}
|
||||
@@ -352,7 +331,7 @@ func (bot *TipBot) satdressCheckInvoiceHandler(ctx intercept.Context) (intercept
|
||||
// save it in the cache for another call later
|
||||
bot.Cache.Set(fmt.Sprintf("invoice:msg:%s", getInvoiceParams.Hash), check_message, &store.Options{Expiration: 24 * time.Hour})
|
||||
|
||||
deadLineCtx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Second*60))
|
||||
deadLineCtx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Second*30))
|
||||
runtime.NewRetryTicker(deadLineCtx, "node_invoice_check", runtime.WithRetryDuration(5*time.Second)).Do(func() {
|
||||
// get invoice from user's node
|
||||
log.Debugf("[satdressCheckInvoiceHandler] Checking invoice: %s", getInvoiceParams.Hash)
|
||||
@@ -448,8 +427,6 @@ func (bot *TipBot) satdressProxyHandler(ctx intercept.Context) (intercept.Contex
|
||||
return ctx, err
|
||||
}
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
|
||||
log.Infof("[node] Proxy payment for user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -462,8 +439,6 @@ func (bot *TipBot) satdressProxyRelayPaymentHandler(event Event) {
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[node:proxy] Relaying payment for user %s backend %s", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
|
||||
bot.notifyInvoiceReceivedEvent(invoiceEvent)
|
||||
|
||||
// now relay the payment to the user's node
|
||||
@@ -506,8 +481,6 @@ func (bot *TipBot) satdressProxyRelayPaymentHandler(event Event) {
|
||||
|
||||
// bot.trySendMessage(user.Telegram, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
|
||||
|
||||
log.Infof("[node:proxy] Retrieved invoice for payment of user %s backend %s. Paying...", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
|
||||
// pay invoice
|
||||
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: getInvoiceParams.PR}, bot.Client)
|
||||
if err != nil {
|
||||
@@ -548,8 +521,6 @@ func (bot *TipBot) satdressProxyRelayPaymentHandler(event Event) {
|
||||
return
|
||||
}
|
||||
bot.tryEditMessage(check_message, invoiceRoutedMessage)
|
||||
|
||||
log.Infof("[node:proxy] Proxy paid for user %s backend %s.", GetUserStr(user.Telegram), user.Settings.Node.NodeType)
|
||||
// bot.trySendMessage(user.Telegram, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
|
||||
|
||||
return
|
||||
|
||||
@@ -113,10 +113,10 @@ func (bot *TipBot) tipHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf("%s: %s", Translate(ctx, "tipErrorMessage"), Translate(ctx, "tipUndefinedErrorMsg")))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf("%s %s", Translate(ctx, "tipErrorMessage"), err))
|
||||
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err.Error())
|
||||
log.Warnln(errMsg)
|
||||
return ctx, err
|
||||
return ctx, fmt.Errorf("could not create wallet for %s", toUserStr)
|
||||
}
|
||||
|
||||
// update tooltip if necessary
|
||||
|
||||
@@ -11,26 +11,26 @@ import (
|
||||
)
|
||||
|
||||
type Transaction struct {
|
||||
ID uint `gorm:"primarykey"`
|
||||
Time time.Time `json:"time"`
|
||||
Bot *TipBot `gorm:"-"`
|
||||
From *lnbits.User `json:"from" gorm:"-"`
|
||||
To *lnbits.User `json:"to" gorm:"-"`
|
||||
FromId int64 `json:"from_id" `
|
||||
ToId int64 `json:"to_id" `
|
||||
FromUser string `json:"from_user"`
|
||||
ToUser string `json:"to_user"`
|
||||
Type string `json:"type"`
|
||||
Amount int64 `json:"amount"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
ChatName string `json:"chat_name"`
|
||||
Memo string `json:"memo"`
|
||||
Success bool `json:"success"`
|
||||
FromWallet string `json:"from_wallet"`
|
||||
ToWallet string `json:"to_wallet"`
|
||||
FromLNbitsID string `json:"from_lnbits"`
|
||||
ToLNbitsID string `json:"to_lnbits"`
|
||||
Invoice lnbits.Invoice `gorm:"embedded;embeddedPrefix:invoice_"`
|
||||
ID uint `gorm:"primarykey"`
|
||||
Time time.Time `json:"time"`
|
||||
Bot *TipBot `gorm:"-"`
|
||||
From *lnbits.User `json:"from" gorm:"-"`
|
||||
To *lnbits.User `json:"to" gorm:"-"`
|
||||
FromId int64 `json:"from_id" `
|
||||
ToId int64 `json:"to_id" `
|
||||
FromUser string `json:"from_user"`
|
||||
ToUser string `json:"to_user"`
|
||||
Type string `json:"type"`
|
||||
Amount int64 `json:"amount"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
ChatName string `json:"chat_name"`
|
||||
Memo string `json:"memo"`
|
||||
Success bool `json:"success"`
|
||||
FromWallet string `json:"from_wallet"`
|
||||
ToWallet string `json:"to_wallet"`
|
||||
FromLNbitsID string `json:"from_lnbits"`
|
||||
ToLNbitsID string `json:"to_lnbits"`
|
||||
Invoice lnbits.BitInvoice `gorm:"embedded;embeddedPrefix:invoice_"`
|
||||
}
|
||||
|
||||
type TransactionOption func(t *Transaction)
|
||||
|
||||
@@ -71,10 +71,6 @@ func (bot *TipBot) GetUserBalanceCached(user *lnbits.User) (amount int64, err er
|
||||
}
|
||||
|
||||
func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
|
||||
if user.Wallet == nil {
|
||||
return 0, errors.New("User has no wallet")
|
||||
}
|
||||
|
||||
wallet, err := bot.Client.Info(*user.Wallet)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[GetUserBalance] Error: Couldn't fetch user %s's info from LNbits: %s", GetUserStr(user.Telegram), err.Error())
|
||||
|
||||
@@ -54,6 +54,7 @@ func startApiServer(bot *telegram.TipBot) {
|
||||
// append lnurl ctx functions
|
||||
lnUrl := lnurl.New(bot)
|
||||
s.AppendRoute("/.well-known/lnurlp/{username}", lnUrl.Handle, http.MethodGet)
|
||||
|
||||
// userpage server
|
||||
userpage := userpage.New(bot)
|
||||
s.AppendRoute("/@{username}", userpage.UserPageHandler, http.MethodGet)
|
||||
@@ -62,16 +63,6 @@ func startApiServer(bot *telegram.TipBot) {
|
||||
hub := lndhub.New(bot)
|
||||
s.AppendRoute(`/lndhub/ext/{.*}`, hub.Handle)
|
||||
s.AppendRoute(`/lndhub/ext`, hub.Handle)
|
||||
//s.AppendAuthorizedRoute(`/lndhub/ext/{.*}`, api.AuthTypeBearer, bot.DB.Users, hub.Handle)
|
||||
//s.AppendAuthorizedRoute(`/lndhub/ext`, api.AuthTypeBearer, bot.DB.Users, hub.Handle)
|
||||
|
||||
// starting api service
|
||||
apiService := api.Service{Bot: bot}
|
||||
s.AppendAuthorizedRoute(`/api/v1/paymentstatus/{payment_hash}`, api.AuthTypeBasic, bot.DB.Users, apiService.PaymentStatus, http.MethodPost)
|
||||
s.AppendAuthorizedRoute(`/api/v1/invoicestatus/{payment_hash}`, api.AuthTypeBasic, bot.DB.Users, apiService.InvoiceStatus, http.MethodPost)
|
||||
s.AppendAuthorizedRoute(`/api/v1/payinvoice`, api.AuthTypeBasic, bot.DB.Users, apiService.PayInvoice, http.MethodPost)
|
||||
s.AppendAuthorizedRoute(`/api/v1/createinvoice`, api.AuthTypeBasic, bot.DB.Users, apiService.CreateInvoice, http.MethodPost)
|
||||
s.AppendAuthorizedRoute(`/api/v1/balance`, api.AuthTypeBasic, bot.DB.Users, apiService.Balance, http.MethodGet)
|
||||
|
||||
// start internal admin server
|
||||
adminService := admin.New(bot)
|
||||
@@ -84,9 +75,6 @@ func startApiServer(bot *telegram.TipBot) {
|
||||
|
||||
}
|
||||
|
||||
func withMiddleware(mw func(w http.ResponseWriter, r *http.Request)) http.HandlerFunc {
|
||||
return mw
|
||||
}
|
||||
func withRecovery() {
|
||||
if r := recover(); r != nil {
|
||||
log.Errorln("Recovered panic: ", r)
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 102 KiB |
@@ -127,10 +127,9 @@ advancedMessage = """%s
|
||||
*/shop* 🛍 Durchsuche shops: `/shop` oder `/shop <user/shop_id>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Gebe Betrag zwuschen %d und %d sat ein."""
|
||||
enterAmountMessage = """💯 Gebe Betrag ein."""
|
||||
enterUserMessage = """👤 Gebe Benutzernamen ein."""
|
||||
errorReasonMessage = """🚫 Fehler: %s"""
|
||||
enterAmountRangeMessage = """⌨️ Gebe einen Betrag zwischen %d und %d sat ein."""
|
||||
enterAmountMessage = """⌨️ Gebe einen Betrag ein."""
|
||||
errorReasonMessage = """🚫 Fehler: %s"""
|
||||
|
||||
# START
|
||||
|
||||
|
||||
@@ -267,7 +267,7 @@ walletConnectMessage = """🔗 *Link your wallet*
|
||||
⚠️ Never share the URL or the QR code with anyone or they will be able to access your funds.
|
||||
|
||||
- *BlueWallet:* Press *New wallet*, *Import wallet*, *Scan or import a file*, and scan the QR code.
|
||||
- *Zeus:* Copy the URL below, press *Add a new node*, select *LNDHub* as Node interface, enter the URL, *Save Node Config*."""
|
||||
- *Zeus:* Copy the URL below, press *Add a new node*, *Import* (the URL), *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Couldn't link your wallet. Please try again later."""
|
||||
linkHiddenMessage = """🔍 Link hidden. Enter /link to see it again."""
|
||||
|
||||
|
||||
Reference in New Issue
Block a user