Compare commits

...
42 Commits
Author SHA1 Message Date
callebtc 5629066ed7 slower 2022-03-01 21:42:36 +03:00
gohumble d7dd0dc4e8 fix redundant int64 cast 2022-02-27 14:04:43 +01:00
gohumble 7ca3ac4a34 fix redundant byte parse 2022-02-27 14:04:09 +01:00
gohumble 9ef0dd0d19 fix state check 2022-02-27 14:03:13 +01:00
gohumble ce7fffb52d fix redundant import 2022-02-27 13:41:11 +01:00
callebtc 3265bae62d Merge branch 'satdress' of github.com:LightningTipBot/LightningTipBot into satdress 2022-02-25 13:03:20 +03:00
callebtc 7285e335ed proxy works 2022-02-25 13:02:50 +03:00
gohumble 3e29400b0c fix context 2022-02-24 15:21:21 +01:00
gohumble 67ee2cdeab Merge remote-tracking branch 'origin/satdress' into satdress
# Conflicts:
#	internal/satdress/satdress.go
#	internal/telegram/satdress.go
2022-02-24 15:19:28 +01:00
gohumble 30d317cb53 retry CheckInvoice 2022-02-24 15:18:09 +01:00
gohumble 68f3500d7a add retry to runtime package 2022-02-24 15:17:31 +01:00
callebtc fc79597ab2 use proxy 2022-02-24 17:08:07 +03:00
gohumble 2756ba0aee fix state check 2022-02-24 14:06:42 +01:00
gohumble 6db890409e error handling 2022-02-24 13:52:28 +01:00
gohumble 0c622e2f18 fix hex conversion 2022-02-24 13:51:45 +01:00
gohumble b25751bbe7 fix params 2022-02-24 13:48:09 +01:00
gohumble 7049cd22f8 fix no certificate check 2022-02-24 13:26:09 +01:00
gohumble 851e4e14f2 fix no certificate check 2022-02-24 13:25:39 +01:00
gohumble 73611dca59 fix lnd invoice request 2022-02-24 13:14:34 +01:00
callebtc 02478970df check invoice 2022-02-24 15:02:34 +03:00
gohumble b486e21984 update lndparams certstring 2022-02-24 10:32:51 +01:00
callebtc a79630fd3a add settings 2022-02-24 12:23:47 +03:00
calleandGitHub 228a02d140 Merge pull request #314 from LightningTipBot/satadress_hmbl
🪄 gorm
2022-02-24 11:23:18 +03:00
gohumble 0cf4aa0f2b 🪄 gorm 2022-02-23 16:35:25 +01:00
callebtc 7accaff321 fix 2022-02-23 17:10:21 +03:00
callebtc f37125a8d9 restore invoice.go 2022-02-23 17:05:21 +03:00
callebtc cd9296e075 wrong db 2022-02-23 17:03:59 +03:00
gohumble 8625467f21 Merge remote-tracking branch 'origin/satdress' into satdress 2022-02-23 15:02:11 +01:00
gohumble 117f2f0619 🪄 gorm 2022-02-23 15:01:15 +01:00
callebtc a9c3f212f6 satdress.go 2022-02-23 16:45:32 +03:00
gohumble 9326ff2f2e Merge branch 'satdress' of https://github.com/LightningTipBot/LightningTipBot into satdress 2022-02-23 14:42:17 +01:00
callebtc 3b35e69a8c fix buttons on lnbits error 2022-02-23 14:43:04 +03:00
callebtc 2c80c057e2 handling 2022-02-23 14:41:14 +03:00
gohumble d35bacfe3d Merge branch 'satdress' of https://github.com/LightningTipBot/LightningTipBot into satdress 2022-02-23 11:57:25 +01:00
callebtc 2b811d2b55 handler 2022-02-23 13:55:25 +03:00
gohumble 21c02d0765 Merge branch 'satdress' of https://github.com/LightningTipBot/LightningTipBot into satdress 2022-02-23 11:53:33 +01:00
callebtc 965146b4cd databases refactor into struct 2022-02-22 13:00:40 +01:00
callebtc ce15e11027 remove duplicate 2022-02-21 08:53:35 +01:00
gohumbleandcallebtc 94fcc39f49 adding parseCertificateToPem 2022-02-20 14:22:05 +01:00
callebtc 1d510fca45 cert 2022-02-20 14:22:05 +01:00
gohumble aa68210ec7 adding parseCertificateToPem 2022-02-09 12:03:33 +01:00
callebtc e5f2353984 cert 2022-02-09 11:09:27 +01:00
19 changed files with 685 additions and 31 deletions
+2 -1
View File
@@ -20,7 +20,8 @@ require (
github.com/sirupsen/logrus v1.6.0
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
github.com/tidwall/buntdb v1.2.7
github.com/tidwall/gjson v1.10.2
github.com/tidwall/gjson v1.12.1
github.com/tidwall/sjson v1.2.4 // indirect
golang.org/x/text v0.3.5
golang.org/x/time v0.0.0-20191024005414-555d28b269f0
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211217193303-c005cce171ac
+4
View File
@@ -508,6 +508,8 @@ github.com/tidwall/gjson v1.6.1 h1:LRbvNuNuvAiISWg6gxLEFuCe72UKy5hDqhxW/8183ws=
github.com/tidwall/gjson v1.6.1/go.mod h1:BaHyNc5bjzYkPqgLq7mdVzeiRtULKULXLgZFKsxEHI0=
github.com/tidwall/gjson v1.10.2 h1:APbLGOM0rrEkd8WBw9C24nllro4ajFuJu0Sc9hRz8Bo=
github.com/tidwall/gjson v1.10.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/gjson v1.12.1 h1:ikuZsLdhr8Ws0IdROXUS1Gi4v9Z4pGqpX/CvJkxvfpo=
github.com/tidwall/gjson v1.12.1/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/grect v0.1.3 h1:z9YwQAMUxVSBde3b7Sl8Da37rffgNfZ6Fq6h9t6KdXE=
github.com/tidwall/grect v0.1.3/go.mod h1:8GMjwh3gPZVpLBI/jDz9uslCe0dpxRpWDdtN0lWAS/E=
github.com/tidwall/lotsa v1.0.2 h1:dNVBH5MErdaQ/xd9s769R31/n2dXavsQ0Yf4TMEHHw8=
@@ -523,6 +525,8 @@ github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/rtred v0.1.2 h1:exmoQtOLvDoO8ud++6LwVsAMTu0KPzLTUrMln8u1yu8=
github.com/tidwall/rtred v0.1.2/go.mod h1:hd69WNXQ5RP9vHd7dqekAz+RIdtfBogmglkZSRxCHFQ=
github.com/tidwall/sjson v1.2.4 h1:cuiLzLnaMeBhRmEv00Lpk3tkYrcxpmbU81tAY4Dw0tc=
github.com/tidwall/sjson v1.2.4/go.mod h1:098SZ494YoMWPmMO6ct4dcFnqxwj9r/gF0Etp19pSNM=
github.com/tidwall/tinyqueue v0.1.1 h1:SpNEvEggbpyN5DIReaJ2/1ndroY8iyEGxPYxoSaymYE=
github.com/tidwall/tinyqueue v0.1.1/go.mod h1:O/QNHwrnjqr6IHItYrzoHAKYhBkLI67Q096fQP5zMYw=
github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
+1 -1
View File
@@ -68,7 +68,7 @@ func (s Service) getUserByTelegramId(r *http.Request) (*lnbits.User, error) {
if v["id"] == "" {
return nil, fmt.Errorf("invalid id")
}
tx := s.bot.Database.Where("telegram_id = ? COLLATE NOCASE", v["id"]).First(user)
tx := s.bot.DB.Users.Where("telegram_id = ? COLLATE NOCASE", v["id"]).First(user)
if tx.Error != nil {
return nil, tx.Error
}
+8
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/satdress"
"github.com/btcsuite/btcd/btcec"
"github.com/imroc/req"
@@ -33,6 +34,13 @@ type User struct {
AnonIDSha256 string `json:"anon_id_sha256"`
UUID string `json:"uuid"`
Banned bool `json:"banned"`
Settings *Settings `json:"settings" gorm:"foreignKey:id"`
}
type Settings struct {
ID string `json:"id" gorm:"primarykey"`
NodeType string `json:"nodetype"`
LNDParams *satdress.LNDParams `gorm:"embedded;embeddedPrefix:lndparams_"`
}
const (
+1 -1
View File
@@ -54,7 +54,7 @@ func NewServer(bot *telegram.TipBot) *Server {
}
apiServer := &Server{
c: bot.Client,
database: bot.Database,
database: bot.DB.Users,
bot: bot.Telegram,
httpServer: srv,
buntdb: bot.Bunt,
+1 -1
View File
@@ -18,7 +18,7 @@ type LndHub struct {
}
func New(bot *telegram.TipBot) LndHub {
return LndHub{database: bot.Database}
return LndHub{database: bot.DB.Users}
}
func (w LndHub) Handle(writer http.ResponseWriter, request *http.Request) {
auth := request.Header.Get("Authorization")
+1 -1
View File
@@ -57,7 +57,7 @@ type Lnurl struct {
func New(bot *telegram.TipBot) Lnurl {
return Lnurl{
c: bot.Client,
database: bot.Database,
database: bot.DB.Users,
callbackHostname: internal.Configuration.Bot.LNURLHostUrl,
WebhookServer: internal.Configuration.Lnbits.WebhookServer,
buntdb: bot.Bunt,
+58
View File
@@ -0,0 +1,58 @@
package runtime
import (
"context"
cmap "github.com/orcaman/concurrent-map"
"time"
)
var retryMap cmap.ConcurrentMap
func init() {
retryMap = cmap.New()
}
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
type FunctionRetry struct {
Ticker *time.Ticker
duration time.Duration
ctx context.Context
name string
}
type FunctionRetryOption func(*FunctionRetry)
func WithRetryDuration(d time.Duration) FunctionRetryOption {
return func(a *FunctionRetry) {
a.duration = d
}
}
func NewRetryTicker(ctx context.Context, name string, option ...FunctionRetryOption) *FunctionRetry {
t := &FunctionRetry{
name: name,
ctx: ctx,
}
for _, opt := range option {
opt(t)
}
if t.duration == 0 {
t.duration = defaultTickerCoolDown
}
t.Ticker = time.NewTicker(t.duration)
return t
}
func (t *FunctionRetry) Do(f func()) {
tickerMap.Set(t.name, t)
go func() {
for {
select {
case <-t.Ticker.C:
// ticker delivered signal. do function f
f()
case <-t.ctx.Done():
return
}
}
}()
}
+226
View File
@@ -0,0 +1,226 @@
package satdress
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
// from github.com/fiatjaf/makeinvoice
var HttpProxyURL = internal.Configuration.Bot.HttpProxy
var Client = &http.Client{
Timeout: 10 * time.Second,
}
type LNDParams struct {
Cert []byte `json:"to" gorm:"-"`
CertString string `json:"certstring"`
Host string `json:"host"`
Macaroon string `json:"macaroon"`
}
func (l LNDParams) getCert() []byte { return l.Cert }
func (l LNDParams) isLocal() bool { return strings.HasPrefix(l.Host, "https://127.0.0.1") }
func (l LNDParams) isTor() bool { return strings.Index(l.Host, ".onion") != -1 }
type BackendParams interface {
getCert() []byte
isTor() bool
isLocal() bool
}
type GetInvoiceParams struct {
Backend BackendParams
Msatoshi int64
Description string
DescriptionHash []byte
Label string // only used for c-lightning
}
type CheckInvoiceParams struct {
Backend BackendParams
PR string
Hash []byte
Status string
}
func GetInvoice(params GetInvoiceParams) (CheckInvoiceParams, error) {
defer func(prevTransport http.RoundTripper) {
Client.Transport = prevTransport
}(Client.Transport)
specialTransport := &http.Transport{}
// use a cert or skip TLS verification?
if len(params.Backend.getCert()) > 0 {
caCertPool := x509.NewCertPool()
ok := caCertPool.AppendCertsFromPEM([]byte(params.Backend.getCert()))
if !ok {
return CheckInvoiceParams{}, fmt.Errorf("invalid root certificate")
}
specialTransport.TLSClientConfig = &tls.Config{RootCAs: caCertPool}
} else {
specialTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
}
// use a proxy?
if !params.Backend.isLocal() && len(HttpProxyURL) > 0 {
proxyURL, _ := url.Parse(HttpProxyURL)
specialTransport.Proxy = http.ProxyURL(proxyURL)
}
Client.Transport = specialTransport
// description hash?
var _, b64h string
if params.DescriptionHash != nil {
_ = hex.EncodeToString(params.DescriptionHash)
b64h = base64.StdEncoding.EncodeToString(params.DescriptionHash)
}
switch backend := params.Backend.(type) {
case LNDParams:
body, _ := sjson.Set("{}", "value_msat", params.Msatoshi)
if params.DescriptionHash == nil {
body, _ = sjson.Set(body, "memo", params.Description)
} else {
body, _ = sjson.Set(body, "description_hash", b64h)
}
req, err := http.NewRequest("POST",
backend.Host+"/v1/invoices",
bytes.NewBufferString(body),
)
if err != nil {
return CheckInvoiceParams{}, err
}
// macaroon must be hex, so if it is on base64 we adjust that
if b, err := base64.StdEncoding.DecodeString(backend.Macaroon); err == nil {
backend.Macaroon = hex.EncodeToString(b)
}
req.Header.Set("Grpc-Metadata-macaroon", backend.Macaroon)
resp, err := Client.Do(req)
if err != nil {
return CheckInvoiceParams{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
body, _ := ioutil.ReadAll(resp.Body)
text := string(body)
if len(text) > 300 {
text = text[:300]
}
return CheckInvoiceParams{}, fmt.Errorf("call to lnd failed (%d): %s", resp.StatusCode, text)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return CheckInvoiceParams{}, err
}
// bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
checkInvoiceParams := CheckInvoiceParams{
Backend: params.Backend,
PR: gjson.ParseBytes(b).Get("payment_request").String(),
Hash: []byte(gjson.ParseBytes(b).Get("r_hash").String()),
Status: "OPEN",
}
return checkInvoiceParams, nil
}
return CheckInvoiceParams{}, errors.New("missing backend params")
}
func CheckInvoice(params CheckInvoiceParams) (CheckInvoiceParams, error) {
defer func(prevTransport http.RoundTripper) {
Client.Transport = prevTransport
}(Client.Transport)
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}
}
// 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:
fmt.Printf("%s", base64.StdEncoding.EncodeToString(params.Hash))
p, err := base64.StdEncoding.DecodeString(string(params.Hash))
if err != nil {
return CheckInvoiceParams{}, fmt.Errorf("invalid hash")
}
hexHash := hex.EncodeToString(p)
requestUrl, err := url.Parse(fmt.Sprintf("%s/v1/invoice/%s?r_hash=%s", backend.Host, hexHash, base64.StdEncoding.EncodeToString(params.Hash)))
if err != nil {
return CheckInvoiceParams{}, err
}
requestUrl.Scheme = "https"
req, err := http.NewRequest("GET",
requestUrl.String(), nil)
if err != nil {
return CheckInvoiceParams{}, err
}
// macaroon must be hex, so if it is on base64 we adjust that
if b, err := base64.StdEncoding.DecodeString(backend.Macaroon); err == nil {
backend.Macaroon = hex.EncodeToString(b)
}
req.Header.Set("Grpc-Metadata-macaroon", backend.Macaroon)
resp, err := Client.Do(req)
if err != nil {
return CheckInvoiceParams{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
body, _ := ioutil.ReadAll(resp.Body)
text := string(body)
if len(text) > 300 {
text = text[:300]
}
return CheckInvoiceParams{}, fmt.Errorf("call to lnd failed (%d): %s", resp.StatusCode, text)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return CheckInvoiceParams{}, err
}
// bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
params.Status = gjson.ParseBytes(b).Get("state").String()
return params, nil
}
return CheckInvoiceParams{}, errors.New("missing backend params")
}
+3 -3
View File
@@ -24,6 +24,7 @@ import (
)
type TipBot struct {
DB *Databases
Database *gorm.DB
Bunt *storage.DB
ShopBunt *storage.DB
@@ -47,12 +48,11 @@ func NewBot() TipBot {
gocacheClient := gocache.New(5*time.Minute, 10*time.Minute)
gocacheStore := store.NewGoCache(gocacheClient, nil)
// create sqlite databases
db, txLogger := AutoMigration()
dbs := AutoMigration()
limiter.Start()
return TipBot{
Database: db,
DB: dbs,
Client: lnbits.NewClient(internal.Configuration.Lnbits.AdminKey, internal.Configuration.Lnbits.Url),
logger: txLogger,
Bunt: createBunt(internal.Configuration.Database.BuntDbPath),
ShopBunt: createBunt(internal.Configuration.Database.ShopBuntDbPath),
Telegram: newTelegramBot(),
+12 -11
View File
@@ -32,8 +32,8 @@ var (
func init() {
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu, btnHelpMainMenu),
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu),
mainMenu.Row(btnBalanceMainMenu),
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu, btnHelpMainMenu),
)
}
@@ -71,15 +71,16 @@ func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
}
if user.Wallet != nil {
amount, err := bot.GetUserBalanceCached(user)
if err == nil {
log.Tracef("[appendMainMenu] user %s balance %d sat", GetUserStr(user.Telegram), amount)
MainMenuCommandBalance := fmt.Sprintf("%s %d sat", MainMenuCommandBalance, amount)
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu),
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu, btnHelpMainMenu),
)
if err != nil {
amount = 0
}
log.Tracef("[appendMainMenu] user %s balance %d sat", GetUserStr(user.Telegram), amount)
MainMenuCommandBalance := fmt.Sprintf("%s %d sat", MainMenuCommandBalance, amount)
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu),
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu, btnHelpMainMenu),
)
}
}
@@ -92,7 +93,7 @@ func (bot *TipBot) makeContactsButtons(ctx context.Context) []tb.Btn {
user := LoadUser(ctx)
// get 5 most recent transactions by from_id with distint to_user
// where to_user starts with an @ and is not the user itself
bot.logger.Where("from_id = ? AND to_user LIKE ? AND to_user <> ?", user.Telegram.ID, "@%", GetUserStr(user.Telegram)).Distinct("to_user").Order("id desc").Limit(5).Find(&records)
bot.DB.Transactions.Where("from_id = ? AND to_user LIKE ? AND to_user <> ?", user.Telegram.ID, "@%", GetUserStr(user.Telegram)).Distinct("to_user").Order("id desc").Limit(5).Find(&records)
log.Debugf("[makeContactsButtons] found %d records", len(records))
// get all contacts and add them to the buttons
+30 -7
View File
@@ -28,6 +28,11 @@ import (
"gorm.io/gorm"
)
type Databases struct {
Users *gorm.DB
Transactions *gorm.DB
}
const (
MessageOrderedByReplyToFrom = "message.reply_to_message.from.id"
TipTooltipKeyPattern = "tip-tool-tip:*"
@@ -86,7 +91,7 @@ func ColumnMigrationTasks(db *gorm.DB) error {
return err
}
func AutoMigration() (db *gorm.DB, txLogger *gorm.DB) {
func AutoMigration() *Databases {
orm, err := gorm.Open(sqlite.Open(internal.Configuration.Database.DbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
if err != nil {
panic("Initialize orm failed.")
@@ -100,7 +105,7 @@ func AutoMigration() (db *gorm.DB, txLogger *gorm.DB) {
panic(err)
}
txLogger, err = gorm.Open(sqlite.Open(internal.Configuration.Database.TransactionsPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
txLogger, err := gorm.Open(sqlite.Open(internal.Configuration.Database.TransactionsPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
if err != nil {
panic("Initialize orm failed.")
}
@@ -108,7 +113,11 @@ func AutoMigration() (db *gorm.DB, txLogger *gorm.DB) {
if err != nil {
panic(err)
}
return orm, txLogger
return &Databases{
Users: orm,
Transactions: txLogger,
}
}
func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.User, error) {
@@ -117,7 +126,7 @@ func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.U
if len(toUserStrWithoutAt) > 100 {
return nil, fmt.Errorf("[GetUserByTelegramUsername] Telegram username is too long: %s..", toUserStrWithoutAt[:100])
}
tx := bot.Database.Where("telegram_username = ? COLLATE NOCASE", toUserStrWithoutAt).First(toUserDb)
tx := bot.DB.Users.Where("telegram_username = ? COLLATE NOCASE", toUserStrWithoutAt).First(toUserDb)
if tx.Error != nil || toUserDb.Wallet == nil {
err := tx.Error
if toUserDb.Wallet == nil {
@@ -144,7 +153,7 @@ func getCachedUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
// without updating the user in storage.
func GetLnbitsUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
tx := bot.Database.First(user)
tx := bot.DB.Users.First(user)
if tx.Error != nil {
errmsg := fmt.Sprintf("[GetUser] Couldn't fetch %s from Database: %s", GetUserStr(u), tx.Error.Error())
log.Warnln(errmsg)
@@ -154,8 +163,22 @@ func GetLnbitsUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
// todo -- unblock this !
return user, nil
}
func GetLnbitsUserWithSettings(u *tb.User, bot TipBot) (*lnbits.User, error) {
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
tx := bot.DB.Users.Preload("Settings").First(user)
if tx.Error != nil {
errmsg := fmt.Sprintf("[GetLnbitsUserWithSettings] Couldn't fetch %s from Database: %s", GetUserStr(u), tx.Error.Error())
log.Warnln(errmsg)
user.Telegram = u
return user, tx.Error
}
if user.Settings == nil {
user.Settings = &lnbits.Settings{ID: user.ID}
}
return user, nil
}
// GetUser from Telegram user. Update the user if user information changed.
// GetUser from Telegram user. Update the user if user information changed.``
func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
var user *lnbits.User
var err error
@@ -236,7 +259,7 @@ func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
log.Errorf("[UpdateUserRecord] UUID empty! Setting to: %s", user.UUID)
}
tx := bot.Database.Save(user)
tx := bot.DB.Users.Save(user)
if tx.Error != nil {
errmsg := fmt.Sprintf("[UpdateUserRecord] Error: Couldn't update %s's info in Database.", GetUserStr(user.Telegram))
log.Errorln(errmsg)
+17
View File
@@ -168,6 +168,23 @@ func (bot TipBot) getHandler() []Handler {
},
},
},
{
Endpoints: []interface{}{"/node"},
Handler: bot.nodeHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.requireUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{"/shops"},
Handler: bot.shopsHandler,
+2
View File
@@ -30,6 +30,7 @@ func initInvoiceEventCallbacks(bot *TipBot) {
InvoiceCallbackGeneric: bot.notifyInvoiceReceivedEvent,
InvoiceCallbackInlineReceive: bot.inlineReceiveEvent,
InvoiceCallbackLNURLPayReceive: bot.lnurlReceiveEvent,
InvoiceCallbackSatdressProxy: bot.satdressProxyRelayPaymentHandler,
}
}
@@ -39,6 +40,7 @@ const (
InvoiceCallbackGeneric = iota + 1
InvoiceCallbackInlineReceive
InvoiceCallbackLNURLPayReceive
InvoiceCallbackSatdressProxy
)
type Invoice struct {
+1 -1
View File
@@ -118,7 +118,7 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) (context.Conte
log.Infof("[/pay] Invoice entered. User: %s, amount: %d sat.", userStr, amount)
// object that holds all information about the send payment
id := fmt.Sprintf("pay-%d-%d-%s", m.Sender.ID, amount, RandStringRunes(5))
id := fmt.Sprintf("pay:%d:%d:%s", m.Sender.ID, amount, RandStringRunes(8))
// // // create inline buttons
payButton := paymentConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "confirm_pay", id)
+311
View File
@@ -0,0 +1,311 @@
package telegram
import (
"bytes"
"context"
"encoding/base64"
"encoding/hex"
"encoding/pem"
"fmt"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/satdress"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/eko/gocache/store"
log "github.com/sirupsen/logrus"
"github.com/skip2/go-qrcode"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
// todo -- rename to something better like parse node settings or something
func parseUserSettingInput(ctx context.Context, m *tb.Message) (satdress.LNDParams, error) {
// input is "/node add <Host> <Macaroon> <Cert>"
params := satdress.LNDParams{}
splits := strings.Split(m.Text, " ")
splitlen := len(splits)
if splitlen < 4 || splitlen > 5 {
return params, fmt.Errorf("Wrong format! Use <Host> <Macaroon> <Cert>")
}
host := splits[2]
macaroon := splits[3]
cert := splits[4]
hostsplit := strings.Split(host, ".")
if len(hostsplit) == 0 {
return params, fmt.Errorf("Host wrong format")
}
pem := parseCertificateToPem(cert)
return satdress.LNDParams{
Cert: pem,
Host: host,
Macaroon: macaroon,
CertString: string(pem),
}, nil
}
func (bot *TipBot) getNodeHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
if err != nil {
log.Infof("Could not get user settings for user %s", GetUserStr(user.Telegram))
return ctx, err
}
node_info_str := "*Host:*\n`%s`\n*Macaroon:*\n`%s`\n*Cert:*\n`%s`"
if user.Settings != nil {
node_info_str_filled := fmt.Sprintf(node_info_str, user.Settings.LNDParams.Host, user.Settings.LNDParams.Macaroon, user.Settings.LNDParams.Cert)
resp_str := fmt.Sprintf("ℹ️ *Your node information.*\n\n%s", node_info_str_filled)
bot.trySendMessage(m.Sender, resp_str)
} else {
bot.trySendMessage(m.Sender, "You did not register a node yet.")
}
return ctx, nil
}
func (bot *TipBot) nodeHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
splits := strings.Split(m.Text, " ")
if len(splits) == 1 {
return bot.getNodeHandler(ctx, m)
} else if len(splits) > 1 {
if splits[1] == "invoice" {
return bot.invHandler(ctx, m)
}
if splits[1] == "add" {
return bot.registerNodeHandler(ctx, m)
}
if splits[1] == "check" {
return bot.satdressCheckInvoiceHandler(ctx, m)
}
if splits[1] == "proxy" {
return bot.satdressProxyHandler(ctx, m)
}
}
return ctx, nil
}
func (bot *TipBot) registerNodeHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
if err != nil {
return ctx, err
}
lndparams, err := parseUserSettingInput(ctx, m)
if err != nil {
return ctx, err
}
user.Settings.LNDParams = &lndparams
user.Settings.NodeType = "lnd"
err = UpdateUserRecord(user, *bot)
node_info_str := "*Host:*\n`%s`\n*Macaroon:*\n`%s`\n*Cert:*\n`%s`"
node_info_str_filled := fmt.Sprintf(node_info_str, lndparams.Host, lndparams.Macaroon, lndparams.Cert)
resp_str := fmt.Sprintf("✅ *Node added.*\n\n%s", node_info_str_filled)
bot.trySendMessage(m.Sender, resp_str)
return ctx, nil
}
func (bot *TipBot) invHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
if err != nil {
return ctx, err
}
if user.Settings == nil || user.Settings.LNDParams == nil {
bot.trySendMessage(m.Sender, "You did not register a node yet.")
return ctx, fmt.Errorf("node of user %s not registered", GetUserStr(user.Telegram))
}
var amount int64
if amount_str, err := getArgumentFromCommand(m.Text, 2); err == nil {
amount, err = getAmount(amount_str)
if err != nil {
return ctx, err
}
}
// get invoice from user's node
getInvoiceParams, err := satdress.GetInvoice(
satdress.GetInvoiceParams{
Backend: satdress.LNDParams{
Cert: []byte(user.Settings.LNDParams.CertString),
Host: user.Settings.LNDParams.Host,
Macaroon: user.Settings.LNDParams.Macaroon,
},
Msatoshi: amount * 1000,
},
)
if err != nil {
log.Errorln(err.Error())
return ctx, err
}
bot.trySendMessage(m.Sender, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
// 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})
return ctx, nil
}
func (bot *TipBot) satdressCheckInvoiceHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
if err != nil {
return ctx, err
}
// get the getInvoiceParams from cache
getInvoiceParamsInterface, err := bot.Cache.Get(fmt.Sprintf("invoice:%d", user.Telegram.ID))
if err != nil {
return ctx, err
}
getInvoiceParams := getInvoiceParamsInterface.(satdress.CheckInvoiceParams)
deadLineCtx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Second*30))
runtime.NewRetryTicker(deadLineCtx, "test", runtime.WithRetryDuration(3*time.Second)).Do(func() {
// get invoice from user's node
getInvoiceParams, err = satdress.CheckInvoice(getInvoiceParams)
if err != nil {
log.Errorln(err.Error())
return
}
if getInvoiceParams.Status == "SETTLED" {
cancel()
}
bot.trySendMessage(m.Sender, fmt.Sprintf("PR: `%s`\n\nHash:`%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
})
return ctx, nil
}
func parseCertificateToPem(cert string) []byte {
block, _ := pem.Decode([]byte(cert))
if block != nil {
// already PEM
return []byte(cert)
} else {
var dec []byte
dec, err := hex.DecodeString(cert)
if err != nil {
// not HEX
dec, err = base64.StdEncoding.DecodeString(cert)
if err != nil {
// not base54, we have a problem huston
return nil
}
}
if block, _ := pem.Decode(dec); block != nil {
return dec
}
// decoding went wrong
return nil
}
}
func (bot *TipBot) satdressProxyHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
if err != nil {
return ctx, err
}
var amount int64
if amount_str, err := getArgumentFromCommand(m.Text, 2); err == nil {
amount, err = getAmount(amount_str)
if err != nil {
return ctx, err
}
}
memo := "Proxy relay invoice"
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, InvoiceCallbackSatdressProxy, "")
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
log.Errorln(errmsg)
return ctx, err
}
// create qr code
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
log.Errorln(errmsg)
return ctx, err
}
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
return ctx, nil
}
func (bot *TipBot) satdressProxyRelayPaymentHandler(invoiceEvent *InvoiceEvent) {
user := invoiceEvent.User
if user.Settings == nil || user.Settings.LNDParams == nil {
bot.trySendMessage(user.Telegram, "You did not register a node yet.")
log.Errorf("node of user %s not registered", GetUserStr(user.Telegram))
return
}
bot.notifyInvoiceReceivedEvent(invoiceEvent)
// now relay the payment to the user's node
var amount int64 = invoiceEvent.Amount
// get invoice from user's node
getInvoiceParams, err := satdress.GetInvoice(
satdress.GetInvoiceParams{
Backend: satdress.LNDParams{
Cert: []byte(user.Settings.LNDParams.CertString),
Host: user.Settings.LNDParams.Host,
Macaroon: user.Settings.LNDParams.Macaroon,
},
Msatoshi: amount * 1000,
},
)
if err != nil {
log.Errorln(err.Error())
return
}
bot.trySendMessage(user.Telegram, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
// pay invoice
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: getInvoiceParams.PR}, bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of %s: %s", GetUserStr(user.Telegram), err)
// err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
// verbose error message, turned off for now
// if len(err.Error()) == 0 {
// err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
// }
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), str.MarkdownEscape(err.Error())), &tb.ReplyMarkup{})
log.Errorln(errmsg)
return
}
// object that holds all information about the send payment
id := fmt.Sprintf("proxypay:%d:%d:%s", user.Telegram.ID, amount, RandStringRunes(8))
payData := &PayData{
Base: storage.New(storage.ID(id)),
From: user,
Invoice: invoice.PaymentRequest,
Hash: invoice.PaymentHash,
Amount: amount,
}
// add result to persistent struct
runtime.IgnoreError(payData.Set(payData, bot.Bunt))
// 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})
time.Sleep(time.Second)
getInvoiceParams, err = satdress.CheckInvoice(getInvoiceParams)
if err != nil {
log.Errorln(err.Error())
return
}
bot.trySendMessage(user.Telegram, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
return
}
+3 -1
View File
@@ -56,8 +56,10 @@ func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
return user, err
}
// set user initialized
user, err := GetUser(tguser, bot)
user, err = GetUser(tguser, bot)
user.Initialized = true
// TODO -- remove this
// user.Settings = &lnbits.Settings{ID: user.Wallet.User, NodeType: "dawgnode"}
err = UpdateUserRecord(user, bot)
if err != nil {
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
+1 -1
View File
@@ -76,7 +76,7 @@ func (t *Transaction) Send() (success bool, err error) {
}
// save transaction to db
tx := t.Bot.logger.Save(t)
tx := t.Bot.DB.Transactions.Save(t)
if tx.Error != nil {
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", err.Error())
log.Errorln(errMsg)
+3 -2
View File
@@ -1,14 +1,15 @@
package main
import (
"net/http"
"runtime/debug"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/api"
"github.com/LightningTipBot/LightningTipBot/internal/api/admin"
"github.com/LightningTipBot/LightningTipBot/internal/lndhub"
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"net/http"
"runtime/debug"
_ "net/http/pprof"