Compare commits

..
Author SHA1 Message Date
gohumble 61c2b898fa rename 2022-06-12 21:42:25 +02:00
gohumble 8d28a3de35 format imports 2022-06-12 21:33:03 +02:00
gohumble e8e5ddb0b3 rename function 2022-06-12 21:32:11 +02:00
gohumble 70cb0a1251 remove unnecessary load 2022-06-12 21:32:00 +02:00
gohumble 303e6d8c41 do todo 2022-06-12 21:31:05 +02:00
gohumble 46f7942022 rename function 2022-06-12 21:30:52 +02:00
gohumble c7adbc7689 error handling 2022-06-12 21:21:24 +02:00
gohumble c702aa2268 error visibility ... 2022-06-12 21:21:07 +02:00
gohumble 31d29df021 fix initWallet 2022-06-12 21:13:43 +02:00
gohumble 1599fc9704 fix comment 2022-06-12 21:07:40 +02:00
gohumble 0ecbb8d58c fix naming 2022-06-12 21:03:37 +02:00
gohumble 2642965052 add comments 2022-06-12 21:03:24 +02:00
gohumble e46470b127 fix start 2022-06-12 21:03:15 +02:00
gohumble 7a8cf08f47 fix errors 2022-06-12 20:49:03 +02:00
gohumble c03e68666d createWallet accepts tb user and returns lnbits user. 2022-06-12 20:44:50 +02:00
gohumble 95aa2a0c92 fix createWallet 2022-06-09 19:31:53 +02:00
gohumble 77c0652e8a add initial wallet 2022-06-06 23:57:38 +03:00
gohumble f6bb0ca47f add initial wallet 2022-06-06 23:51:07 +03:00
gohumble 4b4e518609 try fixing create initial wallet 2022-06-06 23:44:49 +03: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
18 changed files with 270 additions and 176 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"`
+13 -3
View File
@@ -1,6 +1,9 @@
package lnbits
import (
"encoding/json"
"fmt"
"github.com/tidwall/gjson"
"time"
"github.com/imroc/req"
@@ -40,8 +43,8 @@ func (c *Client) GetUser(userId string) (user User, err error) {
return
}
// CreateUserWithInitialWallet creates new user with initial wallet
func (c *Client) CreateUserWithInitialWallet(userName, walletName, adminId string, email string) (wal User, err error) {
// CreateUserWithWallet creates new user with wallet
func (c *Client) CreateUserWithWallet(userName, walletName, adminId string, email string) (user 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"`
@@ -58,7 +61,14 @@ func (c *Client) CreateUserWithInitialWallet(userName, walletName, adminId strin
err = reqErr
return
}
err = resp.ToJSON(&wal)
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)
return
}
+7 -2
View File
@@ -20,6 +20,11 @@ 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"`
@@ -122,8 +127,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")
}
+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.initWallet(bot.Telegram.Me)
_, err := bot.userWithInitWallet(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
}
})
+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
+40 -60
View File
@@ -4,20 +4,16 @@ import (
"context"
stderrors "errors"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"strconv"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal"
log "github.com/sirupsen/logrus"
"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"
)
func (bot TipBot) startHandler(ctx intercept.Context) (intercept.Context, error) {
@@ -29,7 +25,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.initWallet(ctx.Sender())
user, err := bot.userWithInitWallet(ctx.Sender())
if err != nil {
log.Errorln(fmt.Sprintf("[startHandler] Error with initWallet: %s", err.Error()))
bot.tryEditMessage(walletCreationMsg, Translate(ctx, "startWalletErrorMessage"))
@@ -48,74 +44,58 @@ func (bot TipBot) startHandler(ctx intercept.Context) (intercept.Context, error)
return ctx, nil
}
func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
// 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) {
user, err := GetUser(tguser, bot)
if stderrors.Is(err, gorm.ErrRecordNotFound) {
user = &lnbits.User{Telegram: tguser}
err = bot.createWallet(user)
if err != nil {
return user, err
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
}
// 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 {
return nil, err
}
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 {
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
return user, err
return user, fmt.Errorf("[initWallet] error updating user: %v", 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
}
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),
// 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),
internal.Configuration.Lnbits.AdminId,
UserStr)
userStr)
if err != nil {
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err.Error())
log.Errorln(errormsg)
return err
return nil, fmt.Errorf("[createWallet] Create wallet error: %v", err)
}
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.Telegram = u
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
user.AnonIDSha256 = str.AnonIdSha256(user)
user.UUID = str.UUIDSha256(user)
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 {
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err.Error())
log.Errorln(errormsg)
return err
return nil, fmt.Errorf("[createWallet] Update user record error: %v", err)
}
return nil
return &user, nil
}
+1 -7
View File
@@ -100,20 +100,14 @@ 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)
err := bot.createWallet(user)
user, err := bot.createWallet(tbUser)
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.

After

Width:  |  Height:  |  Size: 102 KiB