Compare commits
20
Commits
stringer
...
satdress_v3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
439dd4c0c5 | ||
|
|
aca41ec8dd | ||
|
|
4380955df1 | ||
|
|
4f87cf38bb | ||
|
|
c446b98f8c | ||
|
|
218563f5a1 | ||
|
|
4091bdc399 | ||
|
|
6a2723f35f | ||
|
|
d00b84dbbb | ||
|
|
c23e324476 | ||
|
|
e4db120a3e | ||
|
|
f6cccdad32 | ||
|
|
0227b7ef56 | ||
|
|
0e3748d5cf | ||
|
|
742827687f | ||
|
|
e4eee43db3 | ||
|
|
59e1c25bb1 | ||
|
|
265e5fa3c2 | ||
|
|
c951171256 | ||
|
|
62b3aacee8 |
@@ -4,7 +4,7 @@ go 1.15
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v0.3.1
|
||||
github.com/btcsuite/btcd v0.20.1-beta.0.20200515232429-9f0179fd2c46 // indirect
|
||||
github.com/btcsuite/btcd v0.20.1-beta.0.20200515232429-9f0179fd2c46
|
||||
github.com/eko/gocache v1.2.0
|
||||
github.com/fiatjaf/go-lnurl v1.8.4
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0
|
||||
@@ -12,7 +12,7 @@ require (
|
||||
github.com/imroc/req v0.3.0
|
||||
github.com/jinzhu/configor v1.2.1
|
||||
github.com/makiuchi-d/gozxing v0.0.2
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646
|
||||
github.com/nicksnyder/go-i18n/v2 v2.1.2
|
||||
github.com/orcaman/concurrent-map v1.0.0
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible
|
||||
@@ -20,10 +20,11 @@ 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
|
||||
golang.org/x/text v0.3.5
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0
|
||||
gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220326213923-f323bb71ac8e // indirect
|
||||
gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220326213923-f323bb71ac8e
|
||||
gorm.io/driver/sqlite v1.1.4
|
||||
gorm.io/gorm v1.21.12
|
||||
)
|
||||
|
||||
@@ -521,6 +521,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=
|
||||
@@ -536,6 +538,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=
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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,18 @@ 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"`
|
||||
Node NodeSettings `gorm:"embedded;embeddedPrefix:node_"`
|
||||
}
|
||||
|
||||
type NodeSettings struct {
|
||||
NodeType string `json:"nodetype"`
|
||||
LNDParams *satdress.LNDParams `gorm:"embedded;embeddedPrefix:lndparams_"`
|
||||
LNbitsParams *satdress.LNBitsParams `gorm:"embedded;embeddedPrefix:lnbitsparams_"`
|
||||
}
|
||||
|
||||
const (
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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(), cancel_f func(), deadline_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():
|
||||
if t.ctx.Err() == context.DeadlineExceeded {
|
||||
deadline_f()
|
||||
}
|
||||
if t.ctx.Err() == context.Canceled {
|
||||
cancel_f()
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
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"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
// 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,
|
||||
}
|
||||
|
||||
type LNDParams struct {
|
||||
Cert []byte `json:"cert" 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 LNBitsParams struct {
|
||||
Cert string `json:"certstring"`
|
||||
Host string `json:"host"`
|
||||
Key string `json:"key"`
|
||||
}
|
||||
|
||||
func (l LNBitsParams) getCert() []byte { return []byte(l.Cert) }
|
||||
func (l LNBitsParams) isTor() bool { return strings.Index(l.Host, ".onion") != -1 }
|
||||
func (l LNBitsParams) isLocal() bool { return strings.HasPrefix(l.Host, "https://127.0.0.1") }
|
||||
|
||||
type BackendParams interface {
|
||||
getCert() []byte
|
||||
isTor() bool
|
||||
isLocal() bool
|
||||
}
|
||||
|
||||
type Params 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 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(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 hexh, b64h string
|
||||
if params.DescriptionHash != nil {
|
||||
hexh = hex.EncodeToString(params.DescriptionHash)
|
||||
b64h = base64.StdEncoding.EncodeToString(params.DescriptionHash)
|
||||
}
|
||||
|
||||
switch backend := params.Backend.(type) {
|
||||
case LNDParams:
|
||||
log.Debugf("[MakeInvoice] LND invoice at %s", backend.Host)
|
||||
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
|
||||
|
||||
case LNBitsParams:
|
||||
log.Debugf("[MakeInvoice] LNBits invoice at %s", backend.Host)
|
||||
body, _ := sjson.Set("{}", "amount", params.Msatoshi/1000)
|
||||
body, _ = sjson.Set(body, "out", false)
|
||||
|
||||
if params.DescriptionHash == nil {
|
||||
if params.Description == "" {
|
||||
body, _ = sjson.Set(body, "memo", "invoice")
|
||||
} else {
|
||||
body, _ = sjson.Set(body, "memo", params.Description)
|
||||
}
|
||||
} else {
|
||||
body, _ = sjson.Set(body, "description_hash", hexh)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("POST",
|
||||
backend.Host+"/api/v1/payments",
|
||||
bytes.NewBufferString(body),
|
||||
)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
|
||||
req.Header.Set("X-Api-Key", backend.Key)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
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 lnbits failed (%d): %s", resp.StatusCode, text)
|
||||
}
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
checkInvoiceParams := CheckInvoiceParams{
|
||||
Backend: params.Backend,
|
||||
PR: gjson.ParseBytes(b).Get("payment_request").String(),
|
||||
Hash: []byte(gjson.ParseBytes(b).Get("payment_hash").String()),
|
||||
Status: "OPEN",
|
||||
}
|
||||
return checkInvoiceParams, nil
|
||||
default:
|
||||
return CheckInvoiceParams{}, errors.New("wrong backend type")
|
||||
}
|
||||
}
|
||||
|
||||
func CheckInvoice(params CheckInvoiceParams) (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(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)
|
||||
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
|
||||
}
|
||||
params.Status = gjson.ParseBytes(b).Get("state").String()
|
||||
return params, nil
|
||||
|
||||
case LNBitsParams:
|
||||
log.Debugf("[CheckInvoice] LNBits invoice %s at %s", base64.StdEncoding.EncodeToString(params.Hash), backend.Host)
|
||||
log.Debug("Getting ", backend.Host+"/api/v1/payments/"+string(params.Hash))
|
||||
req, err := http.NewRequest("GET", backend.Host+"/api/v1/payments/"+string(params.Hash), nil)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
|
||||
req.Header.Set("X-Api-Key", backend.Key)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
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 lnbits failed (%d): %s", resp.StatusCode, text)
|
||||
}
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return CheckInvoiceParams{}, err
|
||||
}
|
||||
status := strings.ToLower(gjson.ParseBytes(b).Get("paid").String())
|
||||
if status == "true" {
|
||||
params.Status = "SETTLED"
|
||||
} else {
|
||||
params.Status = "OPEN"
|
||||
}
|
||||
return params, nil
|
||||
default:
|
||||
return CheckInvoiceParams{}, errors.New("missing backend params")
|
||||
}
|
||||
return CheckInvoiceParams{}, errors.New("missing backend params")
|
||||
}
|
||||
@@ -20,15 +20,12 @@ import (
|
||||
gocache "github.com/patrickmn/go-cache"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type TipBot struct {
|
||||
Database *gorm.DB
|
||||
DB *Databases
|
||||
Bunt *storage.DB
|
||||
ShopBunt *storage.DB
|
||||
GroupsDb *gorm.DB
|
||||
logger *gorm.DB
|
||||
Telegram *tb.Bot
|
||||
Client *lnbits.Client
|
||||
limiter map[string]limiter.Limiter
|
||||
@@ -48,17 +45,15 @@ func NewBot() TipBot {
|
||||
gocacheClient := gocache.New(5*time.Minute, 10*time.Minute)
|
||||
gocacheStore := store.NewGoCache(gocacheClient, nil)
|
||||
// create sqlite databases
|
||||
db, txLogger, groupsDb := 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(),
|
||||
Cache: Cache{GoCacheStore: gocacheStore},
|
||||
GroupsDb: groupsDb,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -92,7 +92,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
|
||||
|
||||
@@ -28,6 +28,12 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Databases struct {
|
||||
Users *gorm.DB
|
||||
Transactions *gorm.DB
|
||||
Groups *gorm.DB
|
||||
}
|
||||
|
||||
const (
|
||||
MessageOrderedByReplyToFrom = "message.reply_to_message.from.id"
|
||||
TipTooltipKeyPattern = "tip-tool-tip:*"
|
||||
@@ -86,7 +92,7 @@ func ColumnMigrationTasks(db *gorm.DB) error {
|
||||
return err
|
||||
}
|
||||
|
||||
func AutoMigration() (db *gorm.DB, txLogger *gorm.DB, groupsDb *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 +106,7 @@ func AutoMigration() (db *gorm.DB, txLogger *gorm.DB, groupsDb *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.")
|
||||
}
|
||||
@@ -109,7 +115,7 @@ func AutoMigration() (db *gorm.DB, txLogger *gorm.DB, groupsDb *gorm.DB) {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
groupsDb, err = gorm.Open(sqlite.Open(internal.Configuration.Database.GroupsDbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
groupsDb, err := gorm.Open(sqlite.Open(internal.Configuration.Database.GroupsDbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
if err != nil {
|
||||
panic("Initialize orm failed.")
|
||||
}
|
||||
@@ -117,7 +123,12 @@ func AutoMigration() (db *gorm.DB, txLogger *gorm.DB, groupsDb *gorm.DB) {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return orm, txLogger, groupsDb
|
||||
|
||||
return &Databases{
|
||||
Users: orm,
|
||||
Transactions: txLogger,
|
||||
Groups: groupsDb,
|
||||
}
|
||||
}
|
||||
|
||||
func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.User, error) {
|
||||
@@ -126,7 +137,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 {
|
||||
@@ -153,7 +164,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)
|
||||
@@ -164,6 +175,21 @@ func GetLnbitsUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
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.
|
||||
func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
var user *lnbits.User
|
||||
@@ -245,7 +271,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)
|
||||
|
||||
@@ -139,7 +139,7 @@ func (bot TipBot) groupRequestJoinHandler(ctx intercept.Context) (intercept.Cont
|
||||
groupName := strings.ToLower(splits[splitIdx+1])
|
||||
|
||||
group := &Group{}
|
||||
tx := bot.GroupsDb.Where("name = ? COLLATE NOCASE", groupName).First(group)
|
||||
tx := bot.DB.Groups.Where("name = ? COLLATE NOCASE", groupName).First(group)
|
||||
if tx.Error != nil {
|
||||
bot.trySendMessage(ctx.Message().Chat, Translate(ctx, "groupNotFoundMessage"))
|
||||
return ctx, fmt.Errorf("group not found")
|
||||
@@ -401,7 +401,7 @@ func (bot TipBot) addGroupHandler(ctx intercept.Context) (intercept.Context, err
|
||||
// check if the group with this name is already in db
|
||||
// only if a group with this name is owned by this user, it can be overwritten
|
||||
group := &Group{}
|
||||
tx := bot.GroupsDb.Where("name = ? COLLATE NOCASE", groupName).First(group)
|
||||
tx := bot.DB.Groups.Where("name = ? COLLATE NOCASE", groupName).First(group)
|
||||
if tx.Error == nil {
|
||||
// if it is already added, check if this user is the admin
|
||||
if user.Telegram.ID != group.Owner.ID || group.ID != m.Chat.ID {
|
||||
@@ -437,7 +437,7 @@ func (bot TipBot) addGroupHandler(ctx intercept.Context) (intercept.Context, err
|
||||
Ticket: ticket,
|
||||
}
|
||||
|
||||
bot.GroupsDb.Save(group)
|
||||
bot.DB.Groups.Save(group)
|
||||
log.Infof("[group] Ticket of %d sat added to group %s.", group.Ticket.Price, group.Name)
|
||||
bot.trySendMessage(m.Chat, fmt.Sprintf(Translate(ctx, "groupAddedMessage"), str.MarkdownEscape(m.Chat.Title), group.Name, group.Ticket.Price, GetUserStrMd(bot.Telegram.Me), group.Name))
|
||||
|
||||
|
||||
@@ -148,6 +148,37 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/node"},
|
||||
Handler: bot.nodeHandler,
|
||||
Interceptor: &Interceptor{
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{&btnSatdressCheckInvoice},
|
||||
Handler: bot.satdressCheckInvoiceHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/shops"},
|
||||
Handler: bot.shopsHandler,
|
||||
|
||||
@@ -4,10 +4,11 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
@@ -38,6 +39,7 @@ func initInvoiceEventCallbacks(bot *TipBot) {
|
||||
InvoiceCallbackInlineReceive: EventHandler{Function: bot.inlineReceiveEvent, Type: EventTypeInvoice},
|
||||
InvoiceCallbackLNURLPayReceive: EventHandler{Function: bot.lnurlReceiveEvent, Type: EventTypeInvoice},
|
||||
InvoiceCallbackGroupTicket: EventHandler{Function: bot.groupGetInviteLinkHandler, Type: EventTypeInvoice},
|
||||
InvoiceCallbackSatdressProxy: EventHandler{Function: bot.satdressProxyRelayPaymentHandler, Type: EventTypeInvoice},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +50,7 @@ const (
|
||||
InvoiceCallbackInlineReceive
|
||||
InvoiceCallbackLNURLPayReceive
|
||||
InvoiceCallbackGroupTicket
|
||||
InvoiceCallbackSatdressProxy
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -0,0 +1,527 @@
|
||||
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/telegram/intercept"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
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."
|
||||
checkingInvoiceMessage = "⏳ Checking invoice on your node..."
|
||||
invoiceNotSettledMessage = "❌ Invoice has not settled yet."
|
||||
checkInvoiceButtonMessage = "🔄 Check invoice"
|
||||
routingInvoiceMessage = "🔄 Getting invoice from your node..."
|
||||
checkingNodeMessage = "🔄 Checking your node..."
|
||||
errorCouldNotAddNodeMessage = "❌ Could not add node. Please check your node details."
|
||||
gettingInvoiceOnlyErrorMessage = "❌ Error getting invoice from your node."
|
||||
gettingInvoiceErrorMessage = "❌ Error getting invoice from your node. Your funds are still available."
|
||||
payingInvoiceErrorMessage = "❌ Could not route payment. Your funds are still available."
|
||||
invoiceRoutedMessage = "✅ *Payment routed to your node.*"
|
||||
invoiceSettledMessage = "✅ *Invoice settled.*"
|
||||
nodeAddedMessage = "✅ *Node added.*"
|
||||
satdressCheckInvoicenMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
btnSatdressCheckInvoice = satdressCheckInvoicenMenu.Data(checkInvoiceButtonMessage, "satdress_check_invoice")
|
||||
)
|
||||
|
||||
// todo -- rename to something better like parse node settings or something
|
||||
func parseUserSettingInput(ctx intercept.Context, m *tb.Message) (satdress.BackendParams, error) {
|
||||
// input is "/node add <Type> <Host> <Macaroon> <Cert>"
|
||||
params := satdress.LNDParams{}
|
||||
splits := strings.Split(m.Text, " ")
|
||||
splitlen := len(splits)
|
||||
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>")
|
||||
}
|
||||
host := splits[3]
|
||||
macaroon := splits[4]
|
||||
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
|
||||
} else if strings.ToLower(splits[2]) == "lnbits" {
|
||||
if splitlen < 5 || splitlen > 6 {
|
||||
return params, fmt.Errorf("wrong format. Use <Type> <Host> <Key>")
|
||||
}
|
||||
host := splits[3]
|
||||
key := splits[4]
|
||||
|
||||
host = strings.TrimSuffix(host, "/")
|
||||
hostsplit := strings.Split(host, ".")
|
||||
if len(hostsplit) == 0 {
|
||||
return params, fmt.Errorf("host has wrong format")
|
||||
}
|
||||
return satdress.LNBitsParams{
|
||||
Host: host,
|
||||
Key: key,
|
||||
}, nil
|
||||
}
|
||||
return params, fmt.Errorf("unknown backend type. Supported types: `lnd`, `lnbits`")
|
||||
}
|
||||
|
||||
func nodeInfoString(node *lnbits.NodeSettings) (string, error) {
|
||||
if len(node.NodeType) == 0 {
|
||||
return "", fmt.Errorf("node type is empty")
|
||||
}
|
||||
var node_info_str_filled string
|
||||
var node_info_str string
|
||||
switch strings.ToLower(node.NodeType) {
|
||||
case "lnd":
|
||||
node_info_str = "*Type:* `%s`\n\n*Host:*\n\n`%s`\n\n*Macaroon:*\n\n`%s`\n\n*Cert:*\n\n`%s`"
|
||||
node_info_str_filled = fmt.Sprintf(node_info_str, node.NodeType, node.LNDParams.Host, node.LNDParams.Macaroon, node.LNDParams.CertString)
|
||||
case "lnbits":
|
||||
node_info_str = "*Type:* `%s`\n\n*Host:*\n\n`%s`\n\n*Key:*\n\n`%s`"
|
||||
node_info_str_filled = fmt.Sprintf(node_info_str, node.NodeType, node.LNbitsParams.Host, node.LNbitsParams.Key)
|
||||
default:
|
||||
return "", fmt.Errorf("unknown node type")
|
||||
}
|
||||
return fmt.Sprintf("ℹ️ *Your node information.*\n\n%s", node_info_str_filled), nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) getNodeHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
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
|
||||
}
|
||||
|
||||
if user.Settings == nil {
|
||||
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)
|
||||
return ctx, err
|
||||
}
|
||||
bot.trySendMessage(m.Sender, node_info_str)
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) nodeHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
splits := strings.Split(m.Text, " ")
|
||||
if len(splits) == 1 {
|
||||
return bot.getNodeHandler(ctx)
|
||||
} else if len(splits) > 1 {
|
||||
if splits[1] == "invoice" {
|
||||
return bot.invHandler(ctx)
|
||||
}
|
||||
if splits[1] == "add" {
|
||||
return bot.registerNodeHandler(ctx)
|
||||
}
|
||||
if splits[1] == "check" {
|
||||
return bot.satdressCheckInvoiceHandler(ctx)
|
||||
}
|
||||
if splits[1] == "proxy" {
|
||||
return bot.satdressProxyHandler(ctx)
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) registerNodeHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
check_message := bot.trySendMessageEditable(user.Telegram, checkingNodeMessage)
|
||||
|
||||
backendParams, err := parseUserSettingInput(ctx, m)
|
||||
if err != nil {
|
||||
bot.tryEditMessage(check_message, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
switch backend := backendParams.(type) {
|
||||
case satdress.LNDParams:
|
||||
// get test invoice from user's node
|
||||
getInvoiceParams, err := satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: backend,
|
||||
Msatoshi: 1000,
|
||||
Description: "Test invoice",
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
log.Errorf("[registerNodeHandler] Could not add user %s's %s node: %s", GetUserStr(user.Telegram), getInvoiceParams.Status, err.Error())
|
||||
bot.tryEditMessage(check_message, errorCouldNotAddNodeMessage)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// save node in db
|
||||
user.Settings.Node.LNDParams = &backend
|
||||
user.Settings.Node.NodeType = "lnd"
|
||||
case satdress.LNBitsParams:
|
||||
// get test invoice from user's node
|
||||
getInvoiceParams, err := satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: backend,
|
||||
Msatoshi: 1000,
|
||||
Description: "Test invoice",
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
log.Errorf("[registerNodeHandler] Could not add user %s's %s node: %s", GetUserStr(user.Telegram), getInvoiceParams.Status, err.Error())
|
||||
bot.tryEditMessage(check_message, errorCouldNotAddNodeMessage)
|
||||
return ctx, err
|
||||
}
|
||||
// save node in db
|
||||
user.Settings.Node.LNbitsParams = &backend
|
||||
user.Settings.Node.NodeType = "lnbits"
|
||||
|
||||
}
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
if err != nil {
|
||||
log.Errorf("[registerNodeHandler] could not update record of user %s: %v", GetUserStr(user.Telegram), err)
|
||||
return ctx, err
|
||||
}
|
||||
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)
|
||||
return ctx, err
|
||||
}
|
||||
bot.tryEditMessage(check_message, fmt.Sprintf("%s\n\n%s", node_info_str, nodeAddedMessage))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) invHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
if user.Settings == nil || user.Settings.Node.NodeType == "" {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
check_message := bot.trySendMessageEditable(user.Telegram, routingInvoiceMessage)
|
||||
var getInvoiceParams satdress.CheckInvoiceParams
|
||||
|
||||
if user.Settings.Node.NodeType == "lnd" {
|
||||
// get invoice from user's node
|
||||
getInvoiceParams, err = satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: satdress.LNDParams{
|
||||
Cert: []byte(user.Settings.Node.LNDParams.CertString),
|
||||
Host: user.Settings.Node.LNDParams.Host,
|
||||
Macaroon: user.Settings.Node.LNDParams.Macaroon,
|
||||
},
|
||||
Msatoshi: amount * 1000,
|
||||
Description: fmt.Sprintf("Invoice by %s", GetUserStr(bot.Telegram.Me)),
|
||||
},
|
||||
)
|
||||
} else if user.Settings.Node.NodeType == "lnbits" {
|
||||
// get invoice from user's node
|
||||
getInvoiceParams, err = satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: satdress.LNBitsParams{
|
||||
Key: user.Settings.Node.LNbitsParams.Key,
|
||||
Host: user.Settings.Node.LNbitsParams.Host,
|
||||
},
|
||||
Msatoshi: amount * 1000,
|
||||
Description: fmt.Sprintf("Invoice by %s", GetUserStr(bot.Telegram.Me)),
|
||||
},
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
bot.tryEditMessage(check_message, gettingInvoiceOnlyErrorMessage)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// bot.trySendMessage(m.Sender, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(getInvoiceParams.PR, 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`", getInvoiceParams.PR)})
|
||||
|
||||
// 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})
|
||||
|
||||
// check if invoice settles
|
||||
return bot.satdressCheckInvoiceHandler(ctx)
|
||||
}
|
||||
|
||||
func (bot *TipBot) satdressCheckInvoiceHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
tgUser := LoadUser(ctx).Telegram
|
||||
user, err := GetLnbitsUserWithSettings(tgUser, *bot)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// get the getInvoiceParams from cache
|
||||
log.Debugf("[Cache] Getting key: %s", fmt.Sprintf("invoice:%d", user.Telegram.ID))
|
||||
getInvoiceParamsInterface, err := bot.Cache.Get(fmt.Sprintf("invoice:%d", user.Telegram.ID))
|
||||
if err != nil {
|
||||
log.Errorf("[satdressCheckInvoiceHandler] UserID: %d, %s", user.Telegram.ID, err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
getInvoiceParams := getInvoiceParamsInterface.(satdress.CheckInvoiceParams)
|
||||
|
||||
// check the invoice
|
||||
|
||||
// check if there is an invoice check message in cache already
|
||||
check_message_interface, err := bot.Cache.Get(fmt.Sprintf("invoice:msg:%s", getInvoiceParams.Hash))
|
||||
var check_message *tb.Message
|
||||
if err != nil {
|
||||
// send a new message if there isn't one in the cache
|
||||
check_message = bot.trySendMessageEditable(tgUser, checkingInvoiceMessage)
|
||||
} else {
|
||||
check_message = check_message_interface.(*tb.Message)
|
||||
check_message, err = bot.tryEditMessage(check_message, checkingInvoiceMessage)
|
||||
if err != nil {
|
||||
log.Errorf("[satdressCheckInvoiceHandler] UserID: %d, %s", user.Telegram.ID, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// 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))
|
||||
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)
|
||||
getInvoiceParams, err = satdress.CheckInvoice(getInvoiceParams)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
if getInvoiceParams.Status == "SETTLED" {
|
||||
log.Debugf("[satdressCheckInvoiceHandler] Invoice settled: %s", getInvoiceParams.Hash)
|
||||
bot.tryEditMessage(check_message, invoiceSettledMessage)
|
||||
cancel()
|
||||
}
|
||||
|
||||
}, func() {
|
||||
// cancel
|
||||
},
|
||||
func() {
|
||||
// deadline
|
||||
log.Debugf("[satdressCheckInvoiceHandler] Invoice check expired: %s", getInvoiceParams.Hash)
|
||||
bot.tryEditMessage(check_message, invoiceNotSettledMessage,
|
||||
&tb.ReplyMarkup{
|
||||
InlineKeyboard: [][]tb.InlineButton{
|
||||
{tb.InlineButton{Text: checkInvoiceButtonMessage, Unique: "satdress_check_invoice"}},
|
||||
},
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
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 intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
if user.Settings == nil || user.Settings.Node.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 ctx, fmt.Errorf("no node settings.")
|
||||
}
|
||||
|
||||
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 := "🔀 Payment proxy in."
|
||||
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(event Event) {
|
||||
invoiceEvent := event.(*InvoiceEvent)
|
||||
user := invoiceEvent.User
|
||||
if user.Settings == nil || user.Settings.Node.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
|
||||
|
||||
check_message := bot.trySendMessageEditable(user.Telegram, routingInvoiceMessage)
|
||||
var getInvoiceParams satdress.CheckInvoiceParams
|
||||
var err error
|
||||
if user.Settings.Node.NodeType == "lnd" {
|
||||
// get invoice from user's node
|
||||
getInvoiceParams, err = satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: satdress.LNDParams{
|
||||
Cert: []byte(user.Settings.Node.LNDParams.CertString),
|
||||
Host: user.Settings.Node.LNDParams.Host,
|
||||
Macaroon: user.Settings.Node.LNDParams.Macaroon,
|
||||
},
|
||||
Msatoshi: amount * 1000,
|
||||
Description: fmt.Sprintf("🔀 Payment proxy out from %s.", GetUserStr(bot.Telegram.Me)),
|
||||
},
|
||||
)
|
||||
} else if user.Settings.Node.NodeType == "lnbits" {
|
||||
// get invoice from user's node
|
||||
getInvoiceParams, err = satdress.MakeInvoice(
|
||||
satdress.Params{
|
||||
Backend: satdress.LNBitsParams{
|
||||
Key: user.Settings.Node.LNbitsParams.Key,
|
||||
Host: user.Settings.Node.LNbitsParams.Host,
|
||||
},
|
||||
Msatoshi: amount * 1000,
|
||||
Description: fmt.Sprintf("🔀 Payment proxy out from %s.", GetUserStr(bot.Telegram.Me)),
|
||||
},
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
bot.tryEditMessage(check_message, gettingInvoiceErrorMessage)
|
||||
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)
|
||||
bot.tryEditMessage(check_message, payingInvoiceErrorMessage)
|
||||
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.tryEditMessage(check_message, invoiceRoutedMessage)
|
||||
// bot.trySendMessage(user.Telegram, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
|
||||
|
||||
return
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user