Compare commits

..
6 Commits
Author SHA1 Message Date
998ed1db58 Lnurl (#32)
* dunno

* fix user lookup

* lnurl port

* fix host

* add config example

* amount error msg

* print stack trace

* lnurl_public_server

* remove public server !

* smaller

* smaller

* webhooks

* add tag to response

* add EncodedMetadata and Status

* add success action and empty routes

* update invoice memo

* description hash

* dunno

* fix user lookup

* lnurl port

* fix host

* amount error msg

* add config example

* print stack trace

* lnurl_public_server

* remove public server !

* smaller

* smaller

* webhooks

* add tag to response

* add EncodedMetadata and Status

* add success action and empty routes

* update invoice memo

* description hash

* server log

Co-authored-by: gohumble <lngohumble@gmail.com>
2021-08-30 12:39:54 +02:00
77c3a50c0c Lnurl (#30)
* dunno

* fix user lookup

* lnurl port

* fix host

* add config example

* amount error msg

* print stack trace

* lnurl_public_server

* remove public server !

* smaller

* smaller

* webhooks

* add tag to response

* add EncodedMetadata and Status

* add success action and empty routes

* update invoice memo

* description hash

* dunno

* fix user lookup

* lnurl port

* fix host

* amount error msg

* add config example

* print stack trace

* lnurl_public_server

* remove public server !

* smaller

* smaller

* webhooks

* add tag to response

* add EncodedMetadata and Status

* add success action and empty routes

* update invoice memo

* description hash

Co-authored-by: gohumble <lngohumble@gmail.com>
2021-08-30 12:34:26 +02:00
gohumble f3b3e3440b fix meta data 2021-08-29 23:28:26 +02:00
gohumble 23785a650c update invoice memo 2021-08-29 23:25:54 +02:00
d31e621720 Lnurl (#28)
* dunno

* fix user lookup

* lnurl port

* fix host

* add config example

* amount error msg

* print stack trace

* lnurl_public_server

* remove public server !

* smaller

* smaller

* webhooks

* add tag to response

* add EncodedMetadata and Status

* add success action and empty routes

Co-authored-by: gohumble <lngohumble@gmail.com>
2021-08-29 23:01:01 +02:00
LightningTipBot cae8df6557 fix help 2021-08-29 17:29:57 +02:00
13 changed files with 244 additions and 19 deletions
+1 -1
View File
@@ -82,7 +82,7 @@ The bot replies to a tipped message to indicate to all participants how many and
### Link to BlueWallet or Zap
Every user can link their wallet to an external app like [Bluewallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/) by using the command `/link`. If you host the bot, you will have to enable the LndHub extension in LNbits. You also need to edit the `lnbits_public_url` entry in `config.yaml` accordingly to an address that can be reached.
Every user can link their wallet to an external app like [Bluewallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/) by using the command `/link`. If you host the bot, you will have to enable the LndHub extension in LNbits. You also need to edit the `lnbits_public_url` entry in `config.yaml` accordingly to an address that can be reached by the user's wallet (Tor should be fine as well).
<p align="center">
<img alt="QR code payment example." src="resources/lndhub.png" >
+4
View File
@@ -6,6 +6,8 @@ import (
"sync"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
@@ -126,5 +128,7 @@ func (bot TipBot) Start() {
}
bot.registerTelegramHandlers()
lnbits.NewWebhook(Configuration.WebhookServer, bot.telegram, bot.client, bot.database)
lnurl.NewServer(Configuration.LNURLServer, Configuration.WebhookServer, bot.telegram, bot.client, bot.database)
bot.telegram.Start()
}
+1
View File
@@ -8,6 +8,7 @@ var Configuration = struct {
LnbitsUrl string `json:"lnbits_url" yaml:"lnbits_url"`
LnbitsPublicUrl string `json:"lnbits_public_url" yaml:"lnbits_public_url"`
WebhookServer string `json:"webhook_server" yaml:"webhook_server"`
LNURLServer string `json:"lnurl_public_server" yaml:"lnurl_public_server"`
ApiKey string `json:"telegram_api_key" yaml:"telegram_api_key"`
DbPath string `json:"db_path" yaml:"db_path"`
TransactionsPath string `json:"transactions_path" yaml:"transactions_path"`
+4 -3
View File
@@ -1,7 +1,8 @@
telegram_api_key: "1234"
webhook_server: "http://0.0.0.0:1234"
lnbits_url: "http://127.0.0.1:1234"
lnbits_public_url: "http://*.onion:1234"
webhook_server: "http://0.0.0.0:5588"
lnbits_url: "http://127.0.0.1:5000"
lnbits_public_url: "http://url.com:5000"
lnurl_public_server: "http://url.com:80"
lnbits_admin_key: "1234"
lnbits_admin_id: "3212"
db_path: "data/bot.db"
+9 -9
View File
@@ -29,15 +29,6 @@ var (
endpoint string
)
func init() {
var sb strings.Builder
_, err := io.Copy(&sb, rot13Reader{strings.NewReader("uggcf://ya.gvcf/qbangr/%q?sebz=%f&obg=%f")})
if err != nil {
panic(err)
}
endpoint = sb.String()
}
func helpDonateUsage(errormsg string) string {
if len(errormsg) > 0 {
return fmt.Sprintf(donateHelpText, fmt.Sprintf("%s", errormsg))
@@ -98,6 +89,15 @@ func (bot TipBot) donationHandler(m *tb.Message) {
}
func init() {
var sb strings.Builder
_, err := io.Copy(&sb, rot13Reader{strings.NewReader("uggcf://ya.gvcf/qbangr/%q?sebz=%f&obg=%f")})
if err != nil {
panic(err)
}
endpoint = sb.String()
}
type rot13Reader struct {
r io.Reader
}
+1
View File
@@ -3,6 +3,7 @@ module github.com/LightningTipBot/LightningTipBot
go 1.15
require (
github.com/fiatjaf/go-lnurl v1.4.0
github.com/fiatjaf/ln-decodepay v1.1.0
github.com/gorilla/mux v1.8.0
github.com/imroc/req v0.3.0
+6
View File
@@ -63,6 +63,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
github.com/fiatjaf/go-lnurl v1.4.0 h1:hVFEEJD2A9D6ojEcqLyD54CM2ZJ9Tzs2jNKw/GNq52A=
github.com/fiatjaf/go-lnurl v1.4.0/go.mod h1:BqA8WXAOzntF7Z3EkVO7DfP4y5rhWUmJ/Bu9KBke+rs=
github.com/fiatjaf/ln-decodepay v1.1.0 h1:HigjqNH+ApiO6gm7RV23jXNFuvwq+zgsWl4BJAfPWwE=
github.com/fiatjaf/ln-decodepay v1.1.0/go.mod h1:2qdTT95b8Z4dfuxiZxXuJ1M7bQ9CrLieEA1DKC50q6s=
github.com/frankban/quicktest v1.2.2/go.mod h1:Qh/WofXFeiAFII1aEBu529AtJo6Zg2VHscnEsbBnJ20=
@@ -196,9 +198,13 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/tidwall/gjson v1.6.0/go.mod h1:P256ACg0Mn+j1RXIDXoss50DeIABTYK1PULOJHhxOls=
github.com/tidwall/gjson v1.6.1 h1:LRbvNuNuvAiISWg6gxLEFuCe72UKy5hDqhxW/8183ws=
github.com/tidwall/gjson v1.6.1/go.mod h1:BaHyNc5bjzYkPqgLq7mdVzeiRtULKULXLgZFKsxEHI0=
github.com/tidwall/match v1.0.1 h1:PnKP62LPNxHKTwvHHZZzdOAOCtsJTjo6dZLCwpKm5xc=
github.com/tidwall/match v1.0.1/go.mod h1:LujAq0jyVjBy028G1WhWfIzbpQfMO8bBZ6Tyb0+pL9E=
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/tidwall/pretty v1.0.2 h1:Z7S3cePv9Jwm1KwS0513MRaoUe3S01WPbLNV40pwWZU=
github.com/tidwall/pretty v1.0.2/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/tv42/zbase32 v0.0.0-20160707012821-501572607d02/go.mod h1:tHlrkM198S068ZqfrO6S8HsoJq2bF3ETfTL+kt4tInY=
github.com/urfave/cli v1.18.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
+1 -1
View File
@@ -33,7 +33,7 @@ const (
// "🏛 *Terms*\n" +
// "_We are not custodian of your funds. Any amount you load onto your wallet will be legally considered a donation that belongs to us. We will act in your best interest but we're also aware that the situation without KYC is tricky until we figure something out. Do not give us all your money. Be aware that this bot is in beta development. Use at your own risk._\n\n" +
"❤️ *Donate*\n" +
"_This bot charges no fees but costs satoshis to operate. If you like the bot, please consider supporting this project with a donation. To donate, To donate, use_ `/donate 1000`"
"_This bot charges no fees but costs satoshis to operate. If you like the bot, please consider supporting this project with a donation. To donate, use_ `/donate 1000`"
advancedMessage = "🤖 *Advanced commands*\n\n" +
"*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)\n"
+5 -4
View File
@@ -34,10 +34,11 @@ func (u *User) ResetState() {
}
type InvoiceParams struct {
Out bool `json:"out"`
Amount int64 `json:"amount"`
Memo string `json:"memo"` // the invoice description.
Webhook string `json:"webhook,omitempty"`
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 {
+2 -1
View File
@@ -32,7 +32,7 @@ func NewWebhook(webhookServer string, bot *tb.Bot, client *Client, database *gor
if !strings.Contains(webhookServer, "://") {
log.Fatal("invalid webhook server configuration. please add a scheme.")
}
_, port, err := net.SplitHostPort(strings.Split(webhookServer, "//")[1])
host, port, err := net.SplitHostPort(strings.Split(webhookServer, "//")[1])
if err != nil {
return nil
}
@@ -50,6 +50,7 @@ func NewWebhook(webhookServer string, bot *tb.Bot, client *Client, database *gor
}
apiServer.httpServer.Handler = apiServer.newRouter()
go apiServer.httpServer.ListenAndServe()
log.Infof("[Webhook] Server started at %s port %s", host, port)
return apiServer
}
+208
View File
@@ -0,0 +1,208 @@
package lnurl
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/fiatjaf/go-lnurl"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
"gorm.io/gorm"
)
type Server struct {
httpServer *http.Server
bot *tb.Bot
c *lnbits.Client
database *gorm.DB
callbackUrl string
WebhookServer string
}
const (
lnurlEndpoint = "/.well-known/lnurlp"
minSendable = 1000 // mSat
MaxSendable = 100000000
)
func NewServer(lnurlserver string, webhookserver string, bot *tb.Bot, client *lnbits.Client, database *gorm.DB) *Server {
host, port, err := net.SplitHostPort(strings.Split(lnurlserver, "//")[1])
if err != nil {
return nil
}
srv := &http.Server{
Addr: fmt.Sprintf("0.0.0.0:%s", port),
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
apiServer := &Server{
c: client,
database: database,
bot: bot,
httpServer: srv,
callbackUrl: host,
WebhookServer: webhookserver,
}
apiServer.httpServer.Handler = apiServer.newRouter()
go apiServer.httpServer.ListenAndServe()
log.Infof("[LNURL] Server started at %s port %s", host, port)
return apiServer
}
func (w *Server) newRouter() *mux.Router {
router := mux.NewRouter()
router.HandleFunc(lnurlEndpoint+"/{username}", w.handleLnUrl).Methods(http.MethodGet)
router.HandleFunc("/@{username}", w.handleLnUrl).Methods(http.MethodGet)
//router.HandleFunc("/.well-know/lnurlp/{username}", w.handleLnUrl).Methods(http.MethodGet)
return router
}
func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
if request.URL.RawQuery == "" {
var err error
err = w.serveLNURLpFirst(writer, request)
if err != nil {
log.Errorln(err)
return
}
} else {
w.serveLNURLpSecond(writer, request)
}
}
// descriptionHash is the SHA256 hash of the metadata
func (w Server) descriptionHash(metadata lnurl.Metadata, writer http.ResponseWriter) string {
jsonMeta, err := json.Marshal(metadata)
if err != nil {
writer.WriteHeader(400)
return ""
}
hash := sha256.Sum256([]byte(string(jsonMeta)))
hash_string := hex.EncodeToString(hash[:])
return hash_string
}
// metaData returns the metadata that is sent in the first response
// and is used again in the second response to verify the description hash
func (w Server) metaData(request *http.Request) lnurl.Metadata {
vars := mux.Vars(request)
return lnurl.Metadata{{"text/identifier", fmt.Sprintf("%s@ln.tips", vars["username"])}, {"text/plain", fmt.Sprintf("Pay to %s@%s", vars["username"], w.callbackUrl)}}
}
// serveLNURLpFirst serves the first part of the LNURLp protocol with the endpoint
// to call and the metadata that matches the description hash of the second response
func (w Server) serveLNURLpFirst(writer http.ResponseWriter, request *http.Request) error {
vars := mux.Vars(request)
callback := fmt.Sprintf("%s%s/%s", w.callbackUrl, lnurlEndpoint, vars["username"])
callbackURL, err := url.Parse(callback)
if err != nil {
log.Errorln("callback is not a valid URL")
writer.WriteHeader(400)
return err
}
metadata := w.metaData(request)
jsonMeta, err := json.Marshal(metadata)
if err != nil {
writer.WriteHeader(400)
return err
}
resp := lnurl.LNURLPayResponse1{
LNURLResponse: lnurl.LNURLResponse{Status: "OK"},
Tag: "payRequest",
Callback: fmt.Sprintf("https://%s", callback),
CallbackURL: callbackURL,
MinSendable: minSendable,
MaxSendable: MaxSendable,
CommentAllowed: 512,
EncodedMetadata: string(jsonMeta),
}
jsonResponse, err := json.Marshal(resp)
if err != nil {
writer.WriteHeader(400)
return err
}
writer.WriteHeader(200)
writer.Write(jsonResponse)
return nil
}
// serveLNURLpSecond serves the second LNURL response with the payment request with the correct description hash
func (w Server) serveLNURLpSecond(writer http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
user := &lnbits.User{}
tx := w.database.Where("telegram_username = ?", vars["username"]).First(user)
if tx.Error != nil || user.Wallet == nil || user.Initialized == false {
errmsg := fmt.Sprintf("[GetUser] Couldn't fetch user info from database.")
log.Warnln(errmsg)
return
}
// set wallet lnbits client
user.Wallet.Client = w.c
stringAmount := request.FormValue("amount")
amount, err := strconv.Atoi(stringAmount)
if err != nil {
errmsg := fmt.Sprintf("[serveLNURLpSecond] Couldn't cast amount to int")
log.Warnln(errmsg)
return
}
var resp lnurl.LNURLPayResponse2
if amount < minSendable || amount > MaxSendable {
// amount is not ok
errmsg := fmt.Sprintf("[serveLNURLpSecond] Amount out of bounds")
log.Warnln(errmsg)
resp = lnurl.LNURLPayResponse2{
LNURLResponse: lnurl.LNURLResponse{Status: "ERROR", Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", minSendable, MaxSendable)},
}
} else {
// amount is ok
// the same description_hash needs to be built in the second request
metadata := w.metaData(request)
hash_string := w.descriptionHash(metadata, writer)
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Amount: int64(amount / 1000),
Out: false,
DescriptionHash: hash_string,
Webhook: w.WebhookServer},
*user.Wallet)
if err != nil {
errmsg := fmt.Sprintf("[serveLNURLpSecond] Couldn't create invoice: %s", err.Error())
log.Warnln(errmsg)
resp = lnurl.LNURLPayResponse2{
LNURLResponse: lnurl.LNURLResponse{Status: "ERROR", Reason: "Couldn't create invoice."},
}
} else {
resp = lnurl.LNURLPayResponse2{
LNURLResponse: lnurl.LNURLResponse{Status: "OK"},
PR: invoice.PaymentRequest,
Routes: make([][]lnurl.RouteInfo, 0),
SuccessAction: &lnurl.SuccessAction{Message: "Payment received!", Tag: "message"},
}
}
}
jsonResponse, err := json.Marshal(resp)
if err != nil {
writer.WriteHeader(400)
return
}
writer.Write(jsonResponse)
}
+2
View File
@@ -2,6 +2,7 @@ package main
import (
log "github.com/sirupsen/logrus"
"runtime/debug"
)
// setLogger will initialize the log format
@@ -24,5 +25,6 @@ func main() {
func withRecovery() {
if r := recover(); r != nil {
log.Errorln("Recovered panic: ", r)
debug.PrintStack()
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 172 KiB

After

Width:  |  Height:  |  Size: 107 KiB