Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: generate lightning address for isolated app (WIP) #715

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions alby/alby_oauth_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"golang.org/x/oauth2"
"gorm.io/gorm"

"github.com/getAlby/hub/apps"
"github.com/getAlby/hub/config"
"github.com/getAlby/hub/constants"
"github.com/getAlby/hub/db"
Expand Down Expand Up @@ -346,9 +347,9 @@ func (svc *albyOAuthService) DrainSharedWallet(ctx context.Context, lnClient lnc
10 // Alby fee reserve (10 sats)

if amountSat < 1 {
return errors.New("Not enough balance remaining")
return errors.New("not enough balance remaining")
}
amount := amountSat * 1000
amount := uint64(amountSat * 1000)

logger.Logger.WithField("amount", amount).WithError(err).Error("Draining Alby shared wallet funds")

Expand Down Expand Up @@ -492,7 +493,7 @@ func (svc *albyOAuthService) LinkAccount(ctx context.Context, lnClient lnclient.
scopes = append(scopes, constants.NOTIFICATIONS_SCOPE)
}

app, _, err := db.NewDBService(svc.db, svc.eventPublisher).CreateApp(
app, _, err := apps.NewAppsService(svc.db, svc.eventPublisher).CreateApp(
ALBY_ACCOUNT_APP_NAME,
connectionPubkey,
budget,
Expand Down
80 changes: 71 additions & 9 deletions api/api.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package api

import (
"bytes"
"context"
"encoding/json"
"errors"
Expand All @@ -17,6 +18,7 @@ import (
"gorm.io/gorm"

"github.com/getAlby/hub/alby"
"github.com/getAlby/hub/apps"
"github.com/getAlby/hub/config"
"github.com/getAlby/hub/constants"
"github.com/getAlby/hub/db"
Expand All @@ -33,7 +35,7 @@ import (

type api struct {
db *gorm.DB
dbSvc db.DBService
appsSvc apps.AppsService
cfg config.Config
svc service.Service
permissionsSvc permissions.PermissionsService
Expand All @@ -46,7 +48,7 @@ type api struct {
func NewAPI(svc service.Service, gormDB *gorm.DB, config config.Config, keys keys.Keys, albyOAuthSvc alby.AlbyOAuthService, eventPublisher events.EventPublisher) *api {
return &api{
db: gormDB,
dbSvc: db.NewDBService(gormDB, eventPublisher),
appsSvc: apps.NewAppsService(gormDB, eventPublisher),
cfg: config,
svc: svc,
permissionsSvc: permissions.NewPermissionsService(gormDB, eventPublisher),
Expand All @@ -71,7 +73,7 @@ func (api *api) CreateApp(createAppRequest *CreateAppRequest) (*CreateAppRespons
}
}

app, pairingSecretKey, err := api.dbSvc.CreateApp(
app, pairingSecretKey, err := api.appsSvc.CreateApp(
createAppRequest.Name,
createAppRequest.Pubkey,
createAppRequest.MaxAmountSat,
Expand All @@ -93,9 +95,21 @@ func (api *api) CreateApp(createAppRequest *CreateAppRequest) (*CreateAppRespons
responseBody.Pubkey = app.NostrPubkey
responseBody.PairingSecret = pairingSecretKey

lightningAddress, err := api.albyOAuthSvc.GetLightningAddress()
if err != nil {
return nil, err
var lightningAddress string

if !app.Isolated {
lightningAddress, err = api.albyOAuthSvc.GetLightningAddress()
if err != nil {
return nil, err
}
}

connectionSecret := fmt.Sprintf("nostr+walletconnect://%s?relay=%s&secret=%s", api.keys.GetNostrPublicKey(), relayUrl, pairingSecretKey)
if app.Isolated /* TODO: && createAppRequest.GenerateLightningAddress */ {
lightningAddress, err = api.generateLightningAddress(connectionSecret)
if err != nil {
return nil, err
}
}

if createAppRequest.ReturnTo != "" {
Expand All @@ -104,7 +118,7 @@ func (api *api) CreateApp(createAppRequest *CreateAppRequest) (*CreateAppRespons
query := returnToUrl.Query()
query.Add("relay", relayUrl)
query.Add("pubkey", api.keys.GetNostrPublicKey())
if lightningAddress != "" && !app.Isolated {
if lightningAddress != "" {
query.Add("lud16", lightningAddress)
}
returnToUrl.RawQuery = query.Encode()
Expand All @@ -113,10 +127,10 @@ func (api *api) CreateApp(createAppRequest *CreateAppRequest) (*CreateAppRespons
}

var lud16 string
if lightningAddress != "" && !app.Isolated {
if lightningAddress != "" {
lud16 = fmt.Sprintf("&lud16=%s", lightningAddress)
}
responseBody.PairingUri = fmt.Sprintf("nostr+walletconnect://%s?relay=%s&secret=%s%s", api.keys.GetNostrPublicKey(), relayUrl, pairingSecretKey, lud16)
responseBody.PairingUri = fmt.Sprintf("%s%s", connectionSecret, lud16)
return responseBody, nil
}

Expand Down Expand Up @@ -900,3 +914,51 @@ func (api *api) parseExpiresAt(expiresAtString string) (*time.Time, error) {
}
return expiresAt, nil
}

func (api *api) generateLightningAddress(connectionSecret string) (string, error) {

client := &http.Client{Timeout: 10 * time.Second}

type createUserRequest struct {
ConnectionSecret string `json:"connectionSecret"`
}
request := createUserRequest{
ConnectionSecret: connectionSecret,
}
body := bytes.NewBuffer([]byte{})
err := json.NewEncoder(body).Encode(&request)
if err != nil {
return "", err
}

// TODO: update URL
albyLiteURL := "http://localhost:8081"
req, err := http.NewRequest("POST", fmt.Sprintf("%s/users", albyLiteURL), body)
if err != nil {
return "", err
}

resp, err := client.Do(req)
if err != nil {
logger.Logger.WithError(err).Error("Failed to create new alby lite user")
return "", err
}

if resp.StatusCode >= 300 {
logger.Logger.WithFields(logrus.Fields{
"status": resp.StatusCode,
}).Error("Request to create new alby lite user returned non-success status")
return "", fmt.Errorf("unexpected status code from alby lite: %d", resp.StatusCode)
}

type createUserResponse struct {
LightningAddress string `json:"lightningAddress"`
}
response := &createUserResponse{}
err = json.NewDecoder(resp.Body).Decode(response)
if err != nil {
logger.Logger.WithError(err).Error("Failed to decode API response")
return "", err
}
return response.LightningAddress, nil
}
15 changes: 10 additions & 5 deletions api/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ import (

type API interface {
CreateApp(createAppRequest *CreateAppRequest) (*CreateAppResponse, error)
UpdateApp(userApp *db.App, updateAppRequest *UpdateAppRequest) error
DeleteApp(userApp *db.App) error
GetApp(userApp *db.App) *App
UpdateApp(app *db.App, updateAppRequest *UpdateAppRequest) error
TopupIsolatedApp(ctx context.Context, app *db.App, amountMsat uint64) error
DeleteApp(app *db.App) error
GetApp(app *db.App) *App
ListApps() ([]App, error)
ListChannels(ctx context.Context) ([]Channel, error)
GetChannelPeerSuggestions(ctx context.Context) ([]alby.ChannelPeerSuggestion, error)
Expand All @@ -36,7 +37,7 @@ type API interface {
GetBalances(ctx context.Context) (*BalancesResponse, error)
ListTransactions(ctx context.Context, limit uint64, offset uint64) (*ListTransactionsResponse, error)
SendPayment(ctx context.Context, invoice string) (*SendPaymentResponse, error)
CreateInvoice(ctx context.Context, amount int64, description string) (*MakeInvoiceResponse, error)
CreateInvoice(ctx context.Context, amount uint64, description string) (*MakeInvoiceResponse, error)
LookupInvoice(ctx context.Context, paymentHash string) (*LookupInvoiceResponse, error)
RequestMempoolApi(endpoint string) (interface{}, error)
GetInfo(ctx context.Context) (*InfoResponse, error)
Expand Down Expand Up @@ -86,6 +87,10 @@ type UpdateAppRequest struct {
Metadata Metadata `json:"metadata,omitempty"`
}

type TopupIsolatedAppRequest struct {
AmountSat uint64 `json:"amountSat"`
}

type CreateAppRequest struct {
Name string `json:"name"`
Pubkey string `json:"pubkey"`
Expand Down Expand Up @@ -283,7 +288,7 @@ type SignMessageResponse struct {
}

type MakeInvoiceRequest struct {
Amount int64 `json:"amount"`
Amount uint64 `json:"amount"`
Description string `json:"description"`
}

Expand Down
21 changes: 20 additions & 1 deletion api/transactions.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ import (
"strings"
"time"

"github.com/getAlby/hub/db"
"github.com/getAlby/hub/logger"
"github.com/getAlby/hub/transactions"
"github.com/sirupsen/logrus"
)

func (api *api) CreateInvoice(ctx context.Context, amount int64, description string) (*MakeInvoiceResponse, error) {
func (api *api) CreateInvoice(ctx context.Context, amount uint64, description string) (*MakeInvoiceResponse, error) {
if api.svc.GetLNClient() == nil {
return nil, errors.New("LNClient not started")
}
Expand Down Expand Up @@ -116,6 +117,24 @@ func toApiTransaction(transaction *transactions.Transaction) *Transaction {
}
}

func (api *api) TopupIsolatedApp(ctx context.Context, userApp *db.App, amountMsat uint64) error {
if api.svc.GetLNClient() == nil {
return errors.New("LNClient not started")
}
if !userApp.Isolated {
return errors.New("app is not isolated")
}

transaction, err := api.svc.GetTransactionsService().MakeInvoice(ctx, amountMsat, "top up", "", 0, nil, api.svc.GetLNClient(), &userApp.ID, nil)

if err != nil {
return err
}

_, err = api.svc.GetTransactionsService().SendPaymentSync(ctx, transaction.PaymentRequest, api.svc.GetLNClient(), nil, nil)
return err
}

func toApiBoostagram(boostagram *transactions.Boostagram) *Boostagram {
return &Boostagram{
AppName: boostagram.AppName,
Expand Down
29 changes: 22 additions & 7 deletions db/db_service.go → apps/apps_service.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package db
package apps

import (
"encoding/hex"
Expand All @@ -9,26 +9,32 @@ import (
"time"

"github.com/getAlby/hub/constants"
"github.com/getAlby/hub/db"
"github.com/getAlby/hub/events"
"github.com/getAlby/hub/logger"
"github.com/nbd-wtf/go-nostr"
"gorm.io/datatypes"
"gorm.io/gorm"
)

type dbService struct {
type AppsService interface {
CreateApp(name string, pubkey string, maxAmountSat uint64, budgetRenewal string, expiresAt *time.Time, scopes []string, isolated bool, metadata map[string]interface{}) (*db.App, string, error)
GetAppByPubkey(pubkey string) *db.App
}

type appsService struct {
db *gorm.DB
eventPublisher events.EventPublisher
}

func NewDBService(db *gorm.DB, eventPublisher events.EventPublisher) *dbService {
return &dbService{
func NewAppsService(db *gorm.DB, eventPublisher events.EventPublisher) *appsService {
return &appsService{
db: db,
eventPublisher: eventPublisher,
}
}

func (svc *dbService) CreateApp(name string, pubkey string, maxAmountSat uint64, budgetRenewal string, expiresAt *time.Time, scopes []string, isolated bool, metadata map[string]interface{}) (*App, string, error) {
func (svc *appsService) CreateApp(name string, pubkey string, maxAmountSat uint64, budgetRenewal string, expiresAt *time.Time, scopes []string, isolated bool, metadata map[string]interface{}) (*db.App, string, error) {
if isolated && (slices.Contains(scopes, constants.SIGN_MESSAGE_SCOPE)) {
// cannot sign messages because the isolated app is a custodial subaccount
return nil, "", errors.New("isolated app cannot have sign_message scope")
Expand Down Expand Up @@ -59,7 +65,7 @@ func (svc *dbService) CreateApp(name string, pubkey string, maxAmountSat uint64,
}
}

app := App{Name: name, NostrPubkey: pairingPublicKey, Isolated: isolated, Metadata: datatypes.JSON(metadataBytes)}
app := db.App{Name: name, NostrPubkey: pairingPublicKey, Isolated: isolated, Metadata: datatypes.JSON(metadataBytes)}

err := svc.db.Transaction(func(tx *gorm.DB) error {
err := tx.Save(&app).Error
Expand All @@ -68,7 +74,7 @@ func (svc *dbService) CreateApp(name string, pubkey string, maxAmountSat uint64,
}

for _, scope := range scopes {
appPermission := AppPermission{
appPermission := db.AppPermission{
App: app,
Scope: scope,
ExpiresAt: expiresAt,
Expand Down Expand Up @@ -100,3 +106,12 @@ func (svc *dbService) CreateApp(name string, pubkey string, maxAmountSat uint64,

return &app, pairingSecretKey, nil
}

func (svc *appsService) GetAppByPubkey(pubkey string) *db.App {
dbApp := db.App{}
findResult := svc.db.Where("nostr_pubkey = ?", pubkey).First(&dbApp)
if findResult.RowsAffected == 0 {
return nil
}
return &dbApp
}
4 changes: 0 additions & 4 deletions db/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,6 @@ type Transaction struct {
FailureReason string
}

type DBService interface {
CreateApp(name string, pubkey string, maxAmountSat uint64, budgetRenewal string, expiresAt *time.Time, scopes []string, isolated bool, metadata map[string]interface{}) (*App, string, error)
}

const (
REQUEST_EVENT_STATE_HANDLER_EXECUTING = "executing"
REQUEST_EVENT_STATE_HANDLER_EXECUTED = "executed"
Expand Down
Loading
Loading