Compare commits

..
Author SHA1 Message Date
callebtc 76e354c6ff round logo 2022-04-30 11:22:07 +02:00
callebtc 3a78ef416a new pic 2022-04-30 11:19:13 +02:00
18 changed files with 179 additions and 273 deletions
-1
View File
@@ -23,7 +23,6 @@ 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
+3 -10
View File
@@ -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({
+5 -9
View File
@@ -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
-1
View File
@@ -18,7 +18,6 @@ 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"`
+3 -13
View File
@@ -1,9 +1,6 @@
package lnbits
import (
"encoding/json"
"fmt"
"github.com/tidwall/gjson"
"time"
"github.com/imroc/req"
@@ -43,8 +40,8 @@ func (c *Client) GetUser(userId string) (user User, err error) {
return
}
// CreateUserWithWallet creates new user with wallet
func (c *Client) CreateUserWithWallet(userName, walletName, adminId string, email string) (user User, err error) {
// CreateUserWithInitialWallet creates new user with initial wallet
func (c *Client) CreateUserWithInitialWallet(userName, walletName, adminId string, email string) (wal User, err error) {
resp, err := req.Post(c.url+"/usermanager/api/v1/users", c.header, req.BodyJSON(struct {
WalletName string `json:"wallet_name"`
AdminId string `json:"admin_id"`
@@ -61,14 +58,7 @@ func (c *Client) CreateUserWithWallet(userName, walletName, adminId string, emai
err = reqErr
return
}
err = resp.ToJSON(&user)
res := gjson.Get(resp.String(), "wallets.0")
if res.Index == 0 {
err = fmt.Errorf("could not create initial wallet")
return
}
user.Wallet = &Wallet{}
err = json.Unmarshal([]byte(res.Raw), user.Wallet)
err = resp.ToJSON(&wal)
return
}
+2 -7
View File
@@ -20,11 +20,6 @@ type Client struct {
InvoiceKey string
}
// User is a bot user containing lnbits and telegram information.
// This struct is used for orm persistence.
// Users are created, by talking to the bot or by receiving funds (tips, receive, faucet)
// The initialized flag is set true, if user already talked to the bot.
// This is used for the '<- talk to this bot' message when sending tips to new users.
type User struct {
ID string `json:"id"`
Name string `json:"name" gorm:"primaryKey"`
@@ -127,8 +122,8 @@ type Wallet 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"`
-52
View File
@@ -1,52 +0,0 @@
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
}
+42 -54
View File
@@ -2,7 +2,6 @@ package satdress
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
@@ -10,24 +9,25 @@ 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 Client, _ = network.GetSocksClient()
var HttpProxyURL = internal.Configuration.Bot.HttpProxy
var Client = &http.Client{
Timeout: 10 * time.Second,
}
type LNDParams struct {
Cert []byte `json:"cert" gorm:"-"`
@@ -72,15 +72,23 @@ type CheckInvoiceParams struct {
Status string
}
func SetupHttpClient(useProxy bool, cert []byte) (*http.Client, error) {
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")
}
specialTransport := &http.Transport{}
// use a cert or skip TLS verification?
if len(cert) > 0 {
if len(params.Backend.getCert()) > 0 {
caCertPool := x509.NewCertPool()
ok := caCertPool.AppendCertsFromPEM(cert)
ok := caCertPool.AppendCertsFromPEM([]byte(params.Backend.getCert()))
if !ok {
return Client, fmt.Errorf("invalid root certificate")
return CheckInvoiceParams{}, fmt.Errorf("invalid root certificate")
}
specialTransport.TLSClientConfig = &tls.Config{RootCAs: caCertPool}
} else {
@@ -88,41 +96,12 @@ func SetupHttpClient(useProxy bool, cert []byte) (*http.Client, error) {
}
// use a proxy?
var HttpProxyURL = internal.Configuration.Bot.SocksProxy
if useProxy && len(HttpProxyURL) > 0 {
if !params.Backend.isLocal() && 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")
}
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
@@ -182,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:
@@ -235,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")
@@ -245,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)
@@ -342,4 +329,5 @@ func CheckInvoice(params CheckInvoiceParams) (CheckInvoiceParams, error) {
default:
return CheckInvoiceParams{}, errors.New("missing backend params")
}
return CheckInvoiceParams{}, errors.New("missing backend params")
}
+2 -2
View File
@@ -74,9 +74,9 @@ func newTelegramBot() *tb.Bot {
// todo -- may want to derive user wallets from this specific bot wallet (master wallet), since lnbits usermanager extension is able to do that.
func (bot TipBot) initBotWallet() error {
botWalletInitialisation.Do(func() {
_, err := bot.userWithInitWallet(bot.Telegram.Me)
_, err := bot.initWallet(bot.Telegram.Me)
if err != nil {
log.Errorln(fmt.Sprintf("[initBotWallet] ❌ 🧨 ❌ Could not initialize bot wallet: %s", err.Error()))
log.Errorln(fmt.Sprintf("[initBotWallet] Could not initialize bot wallet: %s", err.Error()))
return
}
})
+3 -4
View File
@@ -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:
+2 -4
View File
@@ -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.GetHttpClient()
client, err := bot.GetHttpClient()
if err != nil {
return ctx, err
}
+2 -4
View File
@@ -3,14 +3,12 @@ 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"
@@ -145,7 +143,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
// LnurlPayState loaded
client, err := network.GetHttpClient()
client, err := bot.GetHttpClient()
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
+2 -4
View File
@@ -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"
@@ -266,7 +264,7 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
callbackUrl.RawQuery = qs.Encode()
// lnurlWithdrawState loaded
client, err := network.GetHttpClient()
client, err := bot.GetHttpClient()
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
+19 -11
View File
@@ -4,10 +4,11 @@ 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"
@@ -22,6 +23,21 @@ 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) {
}
@@ -133,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 {
@@ -141,15 +158,6 @@ 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()
@@ -236,7 +244,7 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
// return rawurl, nil, err
// }
client, err := network.GetHttpClient()
client, err := bot.GetHttpClient()
if err != nil {
return "", nil, err
}
+24 -53
View File
@@ -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
+63 -43
View File
@@ -4,16 +4,20 @@ import (
"context"
stderrors "errors"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
"gorm.io/gorm"
"strconv"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/str"
tb "gopkg.in/lightningtipbot/telebot.v3"
"gorm.io/gorm"
)
func (bot TipBot) startHandler(ctx intercept.Context) (intercept.Context, error) {
@@ -25,7 +29,7 @@ func (bot TipBot) startHandler(ctx intercept.Context) (intercept.Context, error)
// bot.helpHandler(m)
log.Printf("[⭐️ /start] New user: %s (%d)\n", GetUserStr(ctx.Sender()), ctx.Sender().ID)
walletCreationMsg := bot.trySendMessageEditable(ctx.Sender(), Translate(ctx, "startSettingWalletMessage"))
user, err := bot.userWithInitWallet(ctx.Sender())
user, err := bot.initWallet(ctx.Sender())
if err != nil {
log.Errorln(fmt.Sprintf("[startHandler] Error with initWallet: %s", err.Error()))
bot.tryEditMessage(walletCreationMsg, Translate(ctx, "startWalletErrorMessage"))
@@ -44,58 +48,74 @@ func (bot TipBot) startHandler(ctx intercept.Context) (intercept.Context, error)
return ctx, nil
}
// userWithInitWallet will ensure that lnbits.User is initialized.
// Initialized users have already talked to the bot,
// therefor they are able to receive messages from the bot.
func (bot TipBot) userWithInitWallet(tguser *tb.User) (*lnbits.User, error) {
func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
user, err := GetUser(tguser, bot)
if err != nil {
if stderrors.Is(err, gorm.ErrRecordNotFound) {
user, err = bot.createWallet(tguser)
if err != nil {
return user, err
}
user.Initialized = true
err = UpdateUserRecord(user, bot)
if err != nil {
return user, fmt.Errorf("[initWallet] error updating user: %v", err)
}
return user, nil
if stderrors.Is(err, gorm.ErrRecordNotFound) {
user = &lnbits.User{Telegram: tguser}
err = bot.createWallet(user)
if err != nil {
return user, err
}
return nil, err
}
if !user.Initialized {
// set user initialized
user, err := GetUser(tguser, bot)
user.Initialized = true
err = UpdateUserRecord(user, bot)
if err != nil {
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
return user, err
}
} else if !user.Initialized {
// update all tip tooltips (with the "initialize me" message) that this user might have received before
tipTooltipInitializedHandler(user.Telegram, bot)
user.Initialized = true
err = UpdateUserRecord(user, bot)
if err != nil {
return user, fmt.Errorf("[initWallet] error updating user: %v", err)
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
return user, err
}
} else if user.Initialized {
// wallet is already initialized
return user, nil
} else {
err = fmt.Errorf("could not initialize wallet")
return user, err
}
// wallet is already initialized
return user, nil
}
// createWallet will create a wallet for any telegram user.
func (bot TipBot) createWallet(u *tb.User) (*lnbits.User, error) {
userStr := GetUserStr(u)
user, err := bot.Client.CreateUserWithWallet(strconv.FormatInt(u.ID, 10),
fmt.Sprintf("%d (%s)", u.ID, userStr),
func (bot TipBot) createWallet(user *lnbits.User) error {
UserStr := GetUserStr(user.Telegram)
u, err := bot.Client.CreateUserWithInitialWallet(strconv.FormatInt(user.Telegram.ID, 10),
fmt.Sprintf("%d (%s)", user.Telegram.ID, UserStr),
internal.Configuration.Lnbits.AdminId,
userStr)
UserStr)
if err != nil {
return nil, fmt.Errorf("[createWallet] Create wallet error: %v", err)
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err.Error())
log.Errorln(errormsg)
return err
}
user.Telegram = u
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
user.AnonIDSha256 = str.AnonIdSha256(&user)
user.UUID = str.UUIDSha256(&user)
user.Wallet = &lnbits.Wallet{}
user.ID = u.ID
user.Name = u.Name
wallet, err := bot.Client.Wallets(*user)
if err != nil {
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err.Error())
log.Errorln(errormsg)
return err
}
user.Wallet = &wallet[0]
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
user.AnonIDSha256 = str.AnonIdSha256(user)
user.UUID = str.UUIDSha256(user)
user.Initialized = false
user.CreatedAt = time.Now()
err = UpdateUserRecord(&user, bot)
err = UpdateUserRecord(user, bot)
if err != nil {
return nil, fmt.Errorf("[createWallet] Update user record error: %v", err)
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err.Error())
log.Errorln(errormsg)
return err
}
return &user, nil
return nil
}
+7 -1
View File
@@ -100,14 +100,20 @@ func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, e
if _, exists := bot.UserExists(tbUser); exists {
return nil, fmt.Errorf("user already exists")
}
user := &lnbits.User{Telegram: tbUser}
userStr := GetUserStr(tbUser)
log.Printf("[CreateWalletForTelegramUser] Creating wallet for user %s ... ", userStr)
user, err := bot.createWallet(tbUser)
err := bot.createWallet(user)
if err != nil {
errmsg := fmt.Sprintf("[CreateWalletForTelegramUser] Error: Could not create wallet for user %s", userStr)
log.Errorln(errmsg)
return user, err
}
// todo: remove this. we're doing this already in bot.createWallet().
err = UpdateUserRecord(user, *bot)
if err != nil {
return nil, err
}
log.Printf("[CreateWalletForTelegramUser] Wallet created for user %s. ", userStr)
return user, nil
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 102 KiB