Compare commits

..
Author SHA1 Message Date
gohumble 2cfbacf704 update GetUserStrMd 2022-06-13 08:34:27 +02:00
gohumble df8e198b2e update GetUserStr 2022-06-12 22:25:19 +02:00
d2a63c07a3 Transactions int64 amount (#356)
* webln and image

* transactions with int64 amounts

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-05-31 10:49:42 +02:00
calleandGitHub 5199e4c8c6 Anon lnurl help message (#354)
* webln and image

* anon lnurl output
2022-05-29 16:17:23 +02:00
calleandGitHub 1167392140 Stadress: better help (#353)
* webln and image

* Satdress: better logging and help
2022-05-09 13:44:37 +02:00
calleandGitHub 6c06a4972e Satdress lnd tor (#352)
* webln and image

* Satdress: LND over tor
2022-05-07 21:31:47 +02:00
calleandGitHub 666eecf207 Userpages: site name (#351)
* webln and image

* site_name
2022-05-03 18:04:56 +02:00
calleandGitHub 672402616e webln and image (#350) 2022-05-03 17:32:35 +02:00
calleandGitHub fce4fb9ecc satdress timeout (#349) 2022-05-02 23:50:23 +02:00
1946a0e873 Satdress: Socks Proxy (2) (#348)
* 🚧 using socks

* socks proxy

* refactor http client

* remove comments

* remove comments

Co-authored-by: gohumble <lngohumble@gmail.com>
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-05-02 23:36:51 +02:00
LightningTipBotandGitHub fd531e6719 Revert "Satdress: Socks proxy (#346)" (#347)
This reverts commit 94ff302d15.
2022-05-02 23:28:51 +02:00
94ff302d15 Satdress: Socks proxy (#346)
* 🚧 using socks

* socks proxy

* refactor http client

* remove comments

* remove comments

Co-authored-by: gohumble <lngohumble@gmail.com>
2022-05-02 23:25:41 +02:00
LightningTipBotandGitHub 631c314b31 Revert "random_colors (#344)" (#345)
This reverts commit 307967b61a.
2022-04-30 13:46:57 +02:00
307967b61a random_colors (#344)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 13:35:03 +02:00
a53f8e307a Userpage: ln.tips link (#343)
* small note

* rem instead of px

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 13:08:42 +02:00
6f14fab93b send card template (#342)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 12:04:42 +02:00
99a866854b send_to_card (#341)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 12:02:33 +02:00
21f5abbb25 Userpage metadata (#340)
* new pic

* round logo

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 11:22:43 +02:00
16 changed files with 309 additions and 119 deletions
+1
View File
@@ -23,6 +23,7 @@ require (
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-20210916014120-12bc252f5db8
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
+10 -3
View File
@@ -5,12 +5,15 @@
<!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="https://avatars.githubusercontent.com/u/88730856?v=7">
<meta property="og:image" content="{{.Image}}">
<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>
@@ -37,6 +40,10 @@
.white {
color: #f3f3f3c5;
}
.sm {
color: #f3f3f3c5;
font-size: 1rem;
}
#qr {
display: block;
margin-top: 50px;
@@ -48,7 +55,7 @@
white-space: pre-wrap;
word-wrap: break-word;
word-break: break-all;
font-size: 23px;
font-size: 1.5rem;
}
</style>
@@ -57,7 +64,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({
+9 -5
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"html/template"
"net/http"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
@@ -26,6 +27,8 @@ 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"))
@@ -37,7 +40,7 @@ var Client = &http.Client{
// thank you fiatjaf for this code
func (s Service) getTelegramUserPictureURL(username string) (string, error) {
// with proxy:
// client, err := s.bot.GetHttpClient()
// client, err := s.network.GetHttpClient()
// if err != nil {
// return "", err
// }
@@ -65,7 +68,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 := mux.Vars(r)["username"]
username := strings.ToLower(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)
@@ -74,10 +77,11 @@ func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
return
}
image, err := s.getTelegramUserPictureURL(username)
if err != nil {
log.Errorln("[UserPage]", err)
image = "https://telegram.org/img/t_logo.png"
if err != nil || image == "https://telegram.org/img/t_logo.png" {
// replace the default image
image = botImage
}
if err := tmpl.ExecuteTemplate(w, "userpage", struct {
Username string
Image string
+1
View File
@@ -18,6 +18,7 @@ var Configuration = struct {
type BotConfiguration struct {
HttpProxy string `yaml:"http_proxy"`
SocksProxy string `yaml:"socks_proxy"`
LNURLServer string `yaml:"lnurl_server"`
LNURLServerUrl *url.URL `yaml:"-"`
LNURLHostName string `yaml:"lnurl_public_host_name"`
+2 -2
View File
@@ -122,8 +122,8 @@ type Wallet struct {
type Payments []struct {
CheckingID string `json:"checking_id"`
Pending bool `json:"pending"`
Amount int `json:"amount"`
Fee int `json:"fee"`
Amount int64 `json:"amount"`
Fee int64 `json:"fee"`
Memo string `json:"memo"`
Time int `json:"time"`
Bolt11 string `json:"bolt11"`
+52
View File
@@ -0,0 +1,52 @@
package network
import (
"context"
"net"
"net/http"
"net/url"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
log "github.com/sirupsen/logrus"
"golang.org/x/net/proxy"
)
func 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 GetSocksClient() (*http.Client, error) {
client := http.Client{
Timeout: 10 * time.Second,
}
if internal.Configuration.Bot.SocksProxy != "" {
proxyURL, _ := url.Parse(internal.Configuration.Bot.SocksProxy)
specialTransport := &http.Transport{}
specialTransport.Proxy = http.ProxyURL(proxyURL)
d, err := proxy.SOCKS5("tcp", internal.Configuration.Bot.SocksProxy, nil, &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
}
+54 -42
View File
@@ -2,6 +2,7 @@ package satdress
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
@@ -9,25 +10,24 @@ import (
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/network"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"golang.org/x/net/proxy"
)
// 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,
}
var Client, _ = network.GetSocksClient()
type LNDParams struct {
Cert []byte `json:"cert" gorm:"-"`
@@ -72,23 +72,15 @@ type CheckInvoiceParams struct {
Status string
}
func MakeInvoice(params Params) (CheckInvoiceParams, error) {
defer func(prevTransport http.RoundTripper) {
Client.Transport = prevTransport
}(Client.Transport)
if params.Backend == nil {
return CheckInvoiceParams{}, errors.New("no backend specified")
}
func SetupHttpClient(useProxy bool, cert []byte) (*http.Client, error) {
specialTransport := &http.Transport{}
// use a cert or skip TLS verification?
if len(params.Backend.getCert()) > 0 {
if len(cert) > 0 {
caCertPool := x509.NewCertPool()
ok := caCertPool.AppendCertsFromPEM([]byte(params.Backend.getCert()))
ok := caCertPool.AppendCertsFromPEM(cert)
if !ok {
return CheckInvoiceParams{}, fmt.Errorf("invalid root certificate")
return Client, fmt.Errorf("invalid root certificate")
}
specialTransport.TLSClientConfig = &tls.Config{RootCAs: caCertPool}
} else {
@@ -96,12 +88,41 @@ func MakeInvoice(params Params) (CheckInvoiceParams, error) {
}
// use a proxy?
if !params.Backend.isLocal() && len(HttpProxyURL) > 0 {
var HttpProxyURL = internal.Configuration.Bot.SocksProxy
if useProxy && len(HttpProxyURL) > 0 {
proxyURL, _ := url.Parse(HttpProxyURL)
specialTransport.Proxy = http.ProxyURL(proxyURL)
d, err := proxy.SOCKS5("tcp", HttpProxyURL, nil, &net.Dialer{
Timeout: 20 * time.Second,
Deadline: time.Now().Add(time.Second * 10),
KeepAlive: -1,
})
if err != nil {
return Client, err
}
specialTransport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
return d.Dial(network, addr)
}
}
Client.Transport = specialTransport
return Client, nil
}
func MakeInvoice(params Params) (CheckInvoiceParams, error) {
// defer func(prevTransport http.RoundTripper) {
// Client.Transport = prevTransport
// }(Client.Transport)
if params.Backend == nil {
return CheckInvoiceParams{}, errors.New("no backend specified")
}
Client.Transport = specialTransport
var err error
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
if err != nil {
log.Errorf(err.Error())
return CheckInvoiceParams{}, err
}
// description hash?
var hexh, b64h string
@@ -161,6 +182,9 @@ 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:
@@ -211,6 +235,9 @@ 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")
@@ -218,35 +245,21 @@ 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{}
// 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}
var err error
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
if err != nil {
log.Errorf(err.Error())
return CheckInvoiceParams{}, err
}
// 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)
@@ -329,5 +342,4 @@ func CheckInvoice(params CheckInvoiceParams) (CheckInvoiceParams, error) {
default:
return CheckInvoiceParams{}, errors.New("missing backend params")
}
return CheckInvoiceParams{}, errors.New("missing backend params")
}
+4 -3
View File
@@ -3,6 +3,7 @@ package telegram
import (
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
tb "gopkg.in/lightningtipbot/telebot.v3"
@@ -60,11 +61,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 := UserGetLNURL(fromUser)
lnurl, err := UserGetAnonLNURL(fromUser)
if err == nil {
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("LNURL: `%s`", lnurl)
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Anonymous LNURL: `%s`", lnurl)
}
// this is so stupid:
+4 -2
View File
@@ -4,9 +4,11 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"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/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
@@ -105,7 +107,7 @@ func (bot *TipBot) confirmLnurlAuthHandler(ctx intercept.Context) (intercept.Con
}
var sentsigres lnurl.LNURLResponse
client, err := bot.GetHttpClient()
client, err := network.GetHttpClient()
if err != nil {
return ctx, err
}
+4 -2
View File
@@ -3,12 +3,14 @@ package telegram
import (
"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"
@@ -143,7 +145,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
// LnurlPayState loaded
client, err := bot.GetHttpClient()
client, err := network.GetHttpClient()
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
+4 -2
View File
@@ -4,10 +4,12 @@ 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"
@@ -264,7 +266,7 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
callbackUrl.RawQuery = qs.Encode()
// lnurlWithdrawState loaded
client, err := bot.GetHttpClient()
client, err := network.GetHttpClient()
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
+11 -19
View File
@@ -4,11 +4,10 @@ import (
"bytes"
"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"
@@ -23,21 +22,6 @@ import (
tb "gopkg.in/lightningtipbot/telebot.v3"
)
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) {
}
@@ -149,7 +133,6 @@ 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 {
@@ -158,6 +141,15 @@ 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) {
m := ctx.Message()
@@ -244,7 +236,7 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
// return rawurl, nil, err
// }
client, err := bot.GetHttpClient()
client, err := network.GetHttpClient()
if err != nil {
return "", nil, err
}
+53 -24
View File
@@ -23,7 +23,8 @@ import (
)
var (
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."
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."
checkingInvoiceMessage = "⏳ Checking invoice on your node..."
invoiceNotSettledMessage = "❌ Invoice has not settled yet."
checkInvoiceButtonMessage = "🔄 Check invoice"
@@ -49,29 +50,34 @@ func parseUserSettingInput(ctx intercept.Context, m *tb.Message) (satdress.Backe
if splitlen < 4 {
return params, fmt.Errorf("not enough arguments")
}
if strings.ToLower(splits[2]) == "lnd" {
if splitlen < 6 || splitlen > 7 {
return params, fmt.Errorf("wrong format. Use <Type> <Host> <Macaroon> <Cert>")
switch strings.ToLower(splits[2]) {
case "lnd":
if splitlen < 5 || splitlen > 7 {
return params, fmt.Errorf("wrong format. Use <Type> <Host> <Macaroon> [<Cert>]")
}
host := splits[3]
macaroon := splits[4]
cert := splits[5]
var pem []byte
if splitlen == 6 {
cert := splits[5]
pem := parseCertificateToPem(cert)
if len(pem) < 1 {
return params, fmt.Errorf("certificate has invalid format")
}
}
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
} else if strings.ToLower(splits[2]) == "lnbits" {
case "lnbits":
if splitlen < 5 || splitlen > 6 {
return params, fmt.Errorf("wrong format. Use <Type> <Host> <Key>")
}
@@ -87,8 +93,9 @@ 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) {
@@ -110,6 +117,11 @@ 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)
@@ -119,14 +131,14 @@ func (bot *TipBot) getNodeHandler(ctx intercept.Context) (intercept.Context, err
}
if user.Settings == nil {
bot.trySendMessage(m.Sender, registerNodeMessage)
bot.trySendMessage(m.Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
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)
bot.trySendMessage(m.Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
return ctx, err
}
bot.trySendMessage(m.Sender, node_info_str)
@@ -140,17 +152,17 @@ func (bot *TipBot) nodeHandler(ctx intercept.Context) (intercept.Context, error)
if len(splits) == 1 {
return bot.getNodeHandler(ctx)
} else if len(splits) > 1 {
if splits[1] == "invoice" {
switch strings.ToLower(splits[1]) {
case "invoice":
return bot.invHandler(ctx)
}
if splits[1] == "add" {
case "add":
return bot.registerNodeHandler(ctx)
}
if splits[1] == "check" {
case "check":
return bot.satdressCheckInvoiceHandler(ctx)
}
if splits[1] == "proxy" {
case "proxy":
return bot.satdressProxyHandler(ctx)
case "help":
return bot.nodeHelpHandler(ctx)
}
}
return ctx, nil
@@ -216,10 +228,12 @@ 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)
bot.trySendMessage(m.Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
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
}
@@ -242,10 +256,13 @@ 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
if user.Settings.Node.NodeType == "lnd" {
switch user.Settings.Node.NodeType {
case "lnd":
// get invoice from user's node
getInvoiceParams, err = satdress.MakeInvoice(
satdress.Params{
@@ -258,7 +275,7 @@ func (bot *TipBot) invHandler(ctx intercept.Context) (intercept.Context, error)
Description: fmt.Sprintf("Invoice by %s", GetUserStr(bot.Telegram.Me)),
},
)
} else if user.Settings.Node.NodeType == "lnbits" {
case "lnbits":
// get invoice from user's node
getInvoiceParams, err = satdress.MakeInvoice(
satdress.Params{
@@ -270,6 +287,8 @@ 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())
@@ -292,6 +311,8 @@ 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)
}
@@ -331,7 +352,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*30))
deadLineCtx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Second*60))
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)
@@ -427,6 +448,8 @@ 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
}
@@ -439,6 +462,8 @@ 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
@@ -481,6 +506,8 @@ 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 {
@@ -521,6 +548,8 @@ 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
+14 -15
View File
@@ -27,28 +27,27 @@ func ResetUserState(user *lnbits.User, bot *TipBot) {
}
func GetUserStr(user *tb.User) string {
userStr := fmt.Sprintf("@%s", user.Username)
// if user does not have a username
if len(userStr) < 2 && user.FirstName != "" {
userStr = fmt.Sprintf("%s", user.FirstName)
} else if len(userStr) < 2 {
userStr = fmt.Sprintf("%d", user.ID)
if len(user.Username) == 0 {
if user.FirstName != "" {
return fmt.Sprintf("%s", user.FirstName)
} else {
return fmt.Sprintf("%d", user.ID)
}
}
return userStr
return fmt.Sprintf("@%s", user.Username)
}
func GetUserStrMd(user *tb.User) string {
userStr := fmt.Sprintf("@%s", user.Username)
// if user does not have a username
if len(userStr) < 2 && user.FirstName != "" {
userStr = fmt.Sprintf("[%s](tg://user?id=%d)", user.FirstName, user.ID)
return userStr
} else if len(userStr) < 2 {
userStr = fmt.Sprintf("[%d](tg://user?id=%d)", user.ID, user.ID)
return userStr
if len(user.Username) == 0 {
if user.FirstName != "" {
return fmt.Sprintf("[%s](tg://user?id=%d)", user.FirstName, user.ID)
} else {
return fmt.Sprintf("[%d](tg://user?id=%d)", user.ID, user.ID)
}
} else {
// escape only if user has a username
return str.MarkdownEscape(userStr)
return str.MarkdownEscape(fmt.Sprintf("@%s", user.Username))
}
}
+86
View File
@@ -0,0 +1,86 @@
package telegram
import (
tb "gopkg.in/lightningtipbot/telebot.v3"
"testing"
)
func TestGetUserStr(t *testing.T) {
type args struct {
user *tb.User
}
tests := []struct {
name string
args args
want string
}{
{name: "NoUserName", args: args{user: &tb.User{FirstName: "BotUser", ID: 12351241}}, want: "BotUser"},
{name: "UserName", args: args{user: &tb.User{Username: "Username", FirstName: "BotUser", ID: 12351241}}, want: "@Username"},
{name: "NoUserName", args: args{user: &tb.User{Username: "", FirstName: "", ID: 12351241}}, want: "12351241"},
{name: "NoUserName", args: args{user: &tb.User{Username: "Username", FirstName: "", ID: 12351241}}, want: "@Username"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := GetUserStr(tt.args.user); got != tt.want {
t.Errorf("GetUserStr() = %v, want %v", got, tt.want)
}
})
}
}
func BenchmarkGetUserName(b *testing.B) {
benchmarkGetUserStr(&tb.User{Username: "dawg", ID: 1235123, FirstName: "adolf"}, b)
}
func BenchmarkGetUserStrNoUsername(b *testing.B) {
benchmarkGetUserStr(&tb.User{Username: "", ID: 1235123, FirstName: "adolf"}, b)
}
func BenchmarkGetUserStrNoFirstName(b *testing.B) {
benchmarkGetUserStr(&tb.User{Username: "", ID: 1235123, FirstName: ""}, b)
}
func benchmarkGetUserStr(s *tb.User, b *testing.B) {
for n := 0; n < b.N; n++ {
GetUserStr(s)
}
}
func TestGetUserStrMd(t *testing.T) {
type args struct {
user *tb.User
}
tests := []struct {
name string
args args
want string
}{
{name: "NoUserName", args: args{user: &tb.User{FirstName: "BotUser", ID: 12351241}}, want: "[BotUser](tg://user?id=12351241)"},
{name: "UserName", args: args{user: &tb.User{Username: "Username", FirstName: "BotUser", ID: 12351241}}, want: "@Username"},
{name: "NoUserName", args: args{user: &tb.User{Username: "", FirstName: "", ID: 12351241}}, want: "[12351241](tg://user?id=12351241)"},
{name: "NoUserName", args: args{user: &tb.User{Username: "Username", FirstName: "", ID: 12351241}}, want: "@Username"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := GetUserStrMd(tt.args.user); got != tt.want {
t.Errorf("GetUserStr() = %v, want %v", got, tt.want)
}
})
}
}
func BenchmarkGetUserStrMdName(b *testing.B) {
benchmarkGetUserStrMd(&tb.User{Username: "dawg", ID: 1235123, FirstName: "adolf"}, b)
}
func BenchmarkGetUserStrMdNoUsername(b *testing.B) {
benchmarkGetUserStrMd(&tb.User{Username: "", ID: 1235123, FirstName: "adolf"}, b)
}
func BenchmarkGetUserStrMdNoFirstName(b *testing.B) {
benchmarkGetUserStrMd(&tb.User{Username: "", ID: 1235123, FirstName: ""}, b)
}
func benchmarkGetUserStrMd(s *tb.User, b *testing.B) {
for n := 0; n < b.N; n++ {
GetUserStrMd(s)
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB